2014-12-08 108 views
0

我有2個C++類,其中一個是另一個(公有繼承)的基類。我在這兩個操作符中都執行了過載操作符< <。我想要的是使用子類的< <與基類的< <。C++繼承「toString」

這可能嗎?

我的意思是,假設基類< <超載印刷的「嗨,我的名字是瑞」,我想該子類< <超負荷打印「嗨,我的名字是瑞\ n它的陽光明媚的今天」。

感謝

+3

你嘗試了什麼? – quantdev 2014-12-08 01:50:41

+0

我找不到一種方法使其工作... – nervousDev 2014-12-08 01:52:52

+3

@nervousDev:對,但是你試過的那個沒有「工作」?你需要展示研究證據。 – 2014-12-08 02:09:51

回答

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 <<僅用於允許輸出的操作符語法(即兩個類的實現操作相同,但只需重寫虛擬成員函數即可在子類中更改打印邏輯)。

+0

很好的答案,比我的更優雅! – vsoftco 2014-12-08 02:02:51

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 
+0

是的,類似的東西..我是一個java的傢伙,所以事實上沒有像C++中的東西是令人困惑的xD – nervousDev 2014-12-08 02:23:47

+0

我添加了'operator <<'和'main'函數,並且還設置了'toString( )'爲const,所以現在可以編譯並按原樣運行。 – SHR 2014-12-08 03:00:14

0

你所尋找的是一個虛擬的toString funtion:

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

OP想要使用基類的toString函數作爲子類的toString的一部分 – adam 2014-12-08 02:19:17