【发布时间】:2014-12-08 01:49:52
【问题描述】:
我有 2 个 c++ 类,其中一个是另一个的基类(公共继承)。我在两者中都完成了
这可能吗?
我的意思是,假设基类
谢谢
【问题讨论】:
-
我找不到让它工作的方法...
-
@nervousDev:是的,但是您尝试了什么没有“工作”?您需要出示研究证据。
标签: c++ inheritance c++11 mingw
我有 2 个 c++ 类,其中一个是另一个的基类(公共继承)。我在两者中都完成了
这可能吗?
我的意思是,假设基类
谢谢
【问题讨论】:
标签: c++ inheritance c++11 mingw
你可以通过在基类中定义一个虚成员函数,并从基类的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 << 仅用于允许输出的运算符语法(即两个类的实现操作系统相同,但打印逻辑可以在子类中更改覆盖一个虚拟成员函数)。
【讨论】:
你是故意的吗?
(从重叠的子类函数中使用基类虚函数)
#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
【讨论】:
operator<<和main函数,并将toString()设置为const,所以现在可以编译运行了。
你正在寻找的是一个虚拟的 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");
}
};
【讨论】: