2013-04-02 71 views
1
这里

是2类操作符重载继承上类

class B 
{ 
private: 
    int x; 
public: 
    friend std::istream& operator>>(std::istream& in, B& obj) 
    { 
     in >> obj.x; 
     return in; 
    } 
}; 

class D: public B 
{ 
private: 
    int y; 
public: 
    friend std::istream& operator>>(std::istream& in, D& obj) 
    { 
     //? 
    } 
}; 

有没有我可以在d类重载>>运营商因此将能够访问的元素x B中的任何方式?

+0

更具体,让'x'保护;) – maditya

回答

1

根据你看起来是试图做的,你也可以这样做:

class B 
{ 
private: 
    int x; 
public: 
    friend std::istream& operator>>(std::istream& in, B& obj) 
    { 
     in >> obj.x; 
     return in; 
    } 
}; 

class D: public B 
{ 
private: 
    int y; 
public: 
    friend std::istream& operator>>(std::istream& in, D& obj) 
    { 
     B* cast = static_cast<B*>(&D); //create pointer to base class 
     in >> *B; //this calls the operator>> function of the base class 
    } 
}; 

虽然可能有其他原因使x保护的,而不是私人反正。

1

有没有什么办法可以覆盖D类中的>>操作符,以便他能够访问B中的元素x?

请勿使x私密。

通过使私人,你明确地说,访问它仅限于class B和它的朋友。而从你的问题来看,你似乎不想要那样。

如果是protected相反,你可以访问它为obj.x

+0

这恐怕是行不通的,因为'运营商>>'这里是'D',而不是一个成员函数 –

0

X需要得到保护。否则是不能访问直接从D.

class B 
{ 
protected: 
    int x; 

然后,你可以做

class D: public B 
{ 
private: 
    int y; 
public: 
    friend std::istream& operator>>(std::istream& in, D& obj) 
    { 
     in >> obj.x; 
     return in; 
    } 
}; 
+0

'x'由'D'在某种意义上说,'D'有'x'数据成员继承的朋友。它只是无法访问。 – juanchopanza

+0

固定。 .... .. – 2013-04-02 21:13:24