继承类的操作符重载
Operator overloading on inherited class
这里有两个类
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中的>>
操作符,使其能够访问B中的元素x ?
根据您想要做的事情,您还可以这样做:
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
受保护而不是私有,
我是否可以在类D中重载>>操作符,以便他能够访问B中的元素x ?
不要将x
设为私有
通过将其设置为私有,您明确地表示对它的访问仅限于class B
及其朋友。从你的问题来看,你似乎不希望那样。
如果它是protected
,你可以访问它作为obj.x
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;
}
};
相关文章:
- 重载操作符+:表达式必须是整型或无作用域枚举类型
- 重载操作符
- 如何重载操作符==外模板类使用友元函数
- 重载*操作符,使其在左右两边都工作
- 重载操作符<对于非随机迭代器
- 在c++中重载操作符的时间和原因
- 如何在c++中重载=操作符来通过引用进行复制
- 如何在c++中获取定义为友元的重载操作符的地址
- 使用重载操作符的文件操作表达式没有给出预期的结果
- 重载操作符()
- 重载操作符()并在类内使用
- 类中的重载操作符+
- 定时使用重载操作符
- c++带类的重载操作符
- 用列表容器重载[]操作符
- 重载操作符=
- 任何重载操作符()的静态检测
- 重载操作符以处理类对象
- 在使用另一个类的类中重载操作符==
- 派生类和基类中的重载操作符不同