【问题标题】:C++ Inheritance "toString"C++ 继承“toString”
【发布时间】:2014-12-08 01:49:52
【问题描述】:

我有 2 个 c++ 类,其中一个是另一个的基类(公共继承)。我在两者中都完成了

这可能吗?

我的意思是,假设基类

谢谢

【问题讨论】:

  • 我找不到让它工作的方法...
  • @nervousDev:是的,但是您尝试了什么没有“工作”?您需要出示研究证据。

标签: c++ inheritance c++11 mingw


【解决方案1】:

你可以通过在基类中定义一个虚成员函数,并从基类的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 &lt;&lt; 仅用于允许输出的运算符语法(即两个类的实现操作系统相同,但打印逻辑可以在子类中更改覆盖一个虚拟成员函数)。

【讨论】:

    【解决方案2】:

    你是故意的吗?

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

    #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
    

    【讨论】:

    • 是的,类似的东西.. 我是一个 java 人,所以在 c++ 中没有类似的东西的事实令人困惑 xD
    • 我添加了operator&lt;&lt;main函数,并将toString()设置为const,所以现在可以编译运行了。
    【解决方案3】:

    你正在寻找的是一个虚拟的 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");   
        }   
    };
    

    【讨论】:

    • OP想要使用基类的toString函数作为子类toString的一部分
    猜你喜欢
    • 1970-01-01
    • 2015-04-19
    • 2017-06-13
    • 2012-09-16
    • 2012-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多