gpt4 book ai didi

c++ - 运算符 << 重载继承,为什么我从基类而不是子类获取输入?

转载 作者:搜寻专家 更新时间:2023-10-31 02:16:53 25 4
gpt4 key购买 nike

我有一个类,我们称它为A ,它只有一个字段,aa .我还有一个类(class),B , 它继承类 A , 而不是 aa领域,它也有自己的领域,bb .现在,我重载了 operator << ( cout ) 两个类。我尝试使用多态性,但多态性似乎无法与运算符一起正常工作。我的代码只显示了 aa使用运算符时的字段 cout用于显示对象 obj .

我的意思是,我是否总是需要添加 virtual word 重载子类中基类的函数?如果是这样,我应该如何对运营商做同样的事情,运营商不能是虚拟的......

#include <iostream>
#include <ostream>
using namespace std;

class A
{
protected :
int aa;

public:
A(int aa) {this->aa = aa;}
~A(){}
friend ostream &operator<<(ostream &os, const A& obj);
virtual void show() {cout << "a = " << aa << "\n"; }
};

ostream &operator<<(ostream &os, const A& obj)
{
for(int i=0; i<80; i++)
os << "-";
os << "\n";

os << "a = " << obj.aa << "\n";

for(int i=0; i<80; i++)
os << "-";
os << "\n";

return os;
}

class B : public A
{
private :
int bb;

public:
B(int aa, int bb) : A(aa) {this->bb = bb;}
~B(){}
friend ostream &operator<<(ostream &os, const B& obj);
void show() {cout << "a = " << aa << "\n"; cout << "b = " << bb << "\n";}
};

ostream &operator<<(ostream &os, const B& obj)
{
for(int i=0; i<80; i++)
os << "-";
os << "\n";

os << "a = " << obj.aa << "\n";
os << "b = " << obj.bb << "\n";

for(int i=0; i<80; i++)
os << "-";
os << "\n";

return os;
}


int main()
{
A *obj = new B(2,3);
cout << *obj;
obj->show();
delete obj;

return 0;
}

最佳答案

I mean, do I always need to add the virtual word to overload the function from the base class in a child class? If so, how should I do the same with operators, operators can't be virtual ...

当然可以。但是只有成员函数可以是虚拟的,并且这些运算符不是成员函数 - 它们是全局函数。

在这种情况下,您不能使它们成为成员函数(因为第一个参数不是您的类的实例)。但是您可以创建一个虚拟成员函数并让运算符(operator)调用它:

class A
{
protected:
virtual void print(ostream &);
public:
friend ostream &operator<<(ostream &os, const A& obj);
// ... other stuff ...
};

ostream &operator<<(ostream &os, const A& obj)
{
obj.print(os);
return os;
}

然后覆盖 print而不是 operator<< .

关于c++ - 运算符 << 重载继承,为什么我从基类而不是子类获取输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36438349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com