2014-02-17 492 views
-2

考虑一个带有一些变量的父类a,b,c。如果我从这个父类派生一个子类,子类是否知道变量a,b,c?如果是这样,a,b,c的值是否在这个子类中保持不变?继承的基础知识

+0

请重新考虑您的问题,或者至少发布您的代码,如果可能的话。 – Ademar

回答

0

子类将包含父类变量。

如果子类可以访问它们是另一回事。变量需要至少有一个受保护的可访问性,以便子类能够访问和/或使用它们。

+0

如果将这些变量声明为私有? –

+0

您不能从子类访问它们,只能从父类中访问它们。您可以在父类中创建一个公用函数来设置专用字段。 – martijn

2

OOP语言有来自外部和内部的类确定字段的可见性(“变量”)不同的访问级别。 大部分面向对象程序设计语言至少有以下三种:private,protectedpublic。如果你的基类变量是private,派生类不能看到他们,如果他们是protected他们可以(但非派生类不能),如果他们是public每个人都可以看到他们 - 包括衍生和非相关的类。

当然,在基类的方法可以基类总是访问私有变量 - 即使在派生类中新加入的方法无法看到它们。这里是C++中的一个例子(其他OOP语言具有相似的语法)。

class Base { 
    private: 
    int a; 
    protected: 
    int b; 
    public: 
    int f() { a = 1; return a + b; } 
} 

class Derived : public Base { 
    public: 
    int g() { 
     // You cannot access a here, so this is illegal: 
     a = 2; 

     // You can access b here, so this is legal: 
     b = 2; 

     // Base::f, or parent::f() in Java, can access a, so this will return 1 + 2 = 3. 
     return Base::f(); 
    } 
} 

class NonRelated { 
    void h() { 
    Derived d; // Create a derived object 

    // Both of these are illegal since neither a nor b is public: 
    d.a = 3; 
    d.b = 4; 

    // You *can* call both f() and g(), because they are both public. 
    // This will return 3. 
    // (Side note: in actual C++, calling d.f() would not be a good idea since a is not initialized). 
    d.g(); 
    } 
} 
+0

这些变量的值会在子类中保持不变吗? –

+0

我明白你在做什么,但问题不明智。子类没有变量的另一个副本:它扩展了基类,这意味着它继承了它的所有变量和函数,但是如果实例化它,则不会获得Base类的实例和Base + Derived类的实例, 或类似的东西。 – CompuChip