我有2个c ++类,其中一个是另一个的基类(公共继承)。我有<<两者都完成了运算符重载。我想要的是使用<< <<<<<<<<基类。
这可能吗?
我的意思是,想象一下基类<<重载打印的“嗨,我的名字是Rui”,我想要那个子类<<过载打印“嗨,我的名字是Rui \ n今天阳光明媚”。
由于
答案 0 :(得分:2)
您可以通过在基类中定义虚拟成员函数并从基类的operator <<
调用它来完成此操作,如下所示:
struct Base {
virtual string show() {return "Hi, my name is Raul";}
};
struct Derived : public Base {
virtual string show() {return "Hi, my name is Raul, and it's sunny today";}
};
ostream& operator <<(ostream& ostr, const Base& val) {
ostr << val.show();
return ostr;
}
现在实际的调度是虚拟完成的,而operator <<
仅用于允许输出的操作符语法(即两个类的实现os相同,但是可以在子类中更改打印逻辑只需覆盖虚拟成员函数。)
答案 1 :(得分:2)
你有意这样吗?
(从重叠的Sub类函数中使用Base类虚函数)
#include <iostream>
#include <string>
using namespace std;
class Base{
public:
virtual string toString()const{
return string("Hi, my name is Rui");
}
};
class Sub: public Base{
public:
virtual string toString()const{
return Base::toString() + string("\nIt's sunny today");
}
};
//this should work for both Base and Sub
ostream& operator <<(ostream& stream, const Base& b){
return stream<<b.toString();
}
int main(){
Base b;
Sub s;
cout<<"Base print:"<<endl<<b<<endl;
cout<<"Sub print:"<<endl<<s<<endl;
return 0;
}
输出是:
Base print:
Hi, my name is Rui
Sub print:
Hi, my name is Rui
It's sunny today
答案 2 :(得分:0)
您正在寻找的是一个虚拟的toString函数:
class base{
public:
virtual string toString(){
return string("Hi, my name is Rui");
}
};
class derived:public base{
public:
virtual string toString(){
return string("Hi, my name is Rui\nIt's sunny today");
}
};