首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++继承"toString“

C++继承"toString“
EN

Stack Overflow用户
提问于 2014-12-08 09:49:53
回答 3查看 2.7K关注 0票数 0

我有两个c++类,其中一个是另一个的基类(公共继承)。我在这两个函数中都执行了<<操作符重载。我想要的是将子类的<<与基类的<<一起使用。

这是可能的吗?

我的意思是,想象一下基类<<重载print的"Hi,my name is Rui“和我想要的子类<<重载print的"Hi,my name is Rui\n nIt‘s sunny”。

谢谢

EN

回答 3

Stack Overflow用户

发布于 2014-12-08 10:02:02

为此,您可以在基类中定义一个虚拟成员函数,并从基类的operator <<调用它,如下所示:

代码语言:javascript
复制
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 <<仅用于允许输出的操作符语法(即,两个类的实现是相同的,但可以通过覆盖虚拟成员函数在子类中简单地更改打印逻辑)。

票数 2
EN

Stack Overflow用户

发布于 2014-12-08 10:06:02

你是不是想做这样的事?

(从重叠的子类函数中使用基类虚函数)

代码语言:javascript
复制
#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;
}

输出为:

代码语言:javascript
复制
Base print:
Hi, my name is Rui
Sub print:
Hi, my name is Rui
It's sunny today
票数 2
EN

Stack Overflow用户

发布于 2014-12-08 10:06:55

您正在寻找的是一个虚拟的toString函数:

代码语言:javascript
复制
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");   
    }   
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27350212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档