2011-03-01 164 views
9

我有一个简单类,如下访问基类成员中派生

class A { 
     protected: 
     int x; 
     }; 

class B:public A 
     { 
     public: 
     int y; 
     void sety(int d) 
     { 
     y=d; 
     } 
     int gety(){ return y;} 
     }; 

int main() 
{ 
B obj; 
obj.sety(10); 
cout<<obj.gety(); 
getch(); 
} 

如何从所导出的class B的实例设置的protected实例变量A::x的值,而无需创建的class A一个实例。

编辑:我们可以使用B的对象访问A::x的值吗?像obj.x

+0

只需访问它。它在B的成员函数中可见。 – Erik 2011-03-01 11:14:32

回答

9

BA,所以创建的B实例被创建的A一个实例。话虽这么说,我不知道您的实际问题是什么,所以这里的一些代码,希望能澄清事情:

class A 
{ 
protected: 
    int x; 
}; 

class B : public A 
{ 
public: 
    int y; 

    int gety() const { return y; } 
    void sety(int d) { y = d; } 

    int getx() const { return x; } 
    void setx(int d) { x = d; } 
}; 

int main() 
{ 
    B obj; 

    // compiles cleanly because B::sety/gety are public 
    obj.sety(10); 
    std::cout << obj.gety() << '\n'; 

    // compiles cleanly because B::setx/getx are public, even though 
    // they touch A::x which is protected 
    obj.setx(42); 
    std::cout << obj.getx() << '\n'; 

    // compiles cleanly because B::y is public 
    obj.y = 20; 
    std::cout << obj.y << '\n'; 

    // compilation errors because A::x is protected 
    obj.x = 84; 
    std::cout << obj.x << '\n'; 
} 

obj可以访问A::x一样的A可能的情况下,因为obj是隐式实例A

+0

可能想提及范围以及如何影响访问。 – reuscam 2011-03-01 11:29:34

+0

@reuscam,为清晰起见编辑(希望) – ildjarn 2011-03-01 11:37:41

0

你只需将它简称为x在B类

例如:

class B : public A 
{ 
public: 
    ... 

    void setx(int d) 
    { 
     x=d; 
    } 
}; 
1

A::x受到保护,因此无法从外部访问,因此无法从A().xB().x访问。然而,在A和那些直接继承它的方法(因为受保护而不是私有)的方法中可以访问,例如, B。因此,不管语义如何,B::sety()都可以访问它(如果是B::x的阴影或纯粹冗长的情况,则为xA::x)。

0

请注意,B不能完全访问A :: x。它只能访问成员通过B,不是A型的任何东西,或从A

派生的实例有一种变通方法,您可以把:

class A 
{ 
    protected: 
    int x; 
    static int& getX(A& a) 
    { 
     return a.x; 
    } 

    static int getX(A const& a) 
    { 
    return a.x; 
    } 
}; 

,现在使用的getX,一类派生自A(如B)可以获得任何A类的x成员。

你也知道友谊不是传递或继承。通过提供访问功能,可以为这些情况制定相同的“解决方法”。

在你的情况下,你可以通过使用公共函数来实际提供通过你的B的“公共”访问。当然,在真正的编程中,它受到保护是有原因的,你不想让所有的东西都能完全访问,但是你可以。

+0

完全正确,但对于初学者,您应该将其与“private”的行为进行对比: – MSalters 2011-03-01 14:46:36

相关问题