2014-02-12 59 views
1

我創建了一個從字符串類公開繼承的新類。我希望超載派生類中的<(小於)運算符。但是從重載函數我需要調用父類<運算符。調用這個函數的語法是什麼?如果可能,我希望將該運算符作爲成員函數來實現。如何從重載函數調用父類成員函數?

在Java中有super這個關鍵字。

我的代碼如下。

#include<iostream> 
#include<string> 
using namespace std;  
class mystring:public string 
    { 
    bool operator<(const mystring ms) 
    { 
     //some stmt; 
     //some stmt; 
     //call the overloaded <(less than)operator in the string class and return the value 
     } 

    }; 
+0

是''string'的std :: string'? –

+0

是std :: string –

+0

謝謝你的link.I需要在父類中調用less運算符的語法。 –

回答

1

std::string不具有operator<一員超載,提供了一種用於operator<自由函數模板,其操作在std::string。你應該考慮讓你的operator<免費的功能。要撥打在std::string上運行的operator<,您可以使用參考。

例如爲:

const std::string& left = *this; 
const std::string& right = ms; 
return left < right; 
+0

非常感謝!這一個完美的作品。 可否請您多回答一個懷疑。如果它是一個免費函數模板,默認情況下它應該也適用於mystring。但是,當我從mystr中刪除運算符<函數時,編譯器會給出錯誤。 –

+0

@AbleJohnson:編譯器給出了什麼錯誤,以及給出這個錯誤的代碼實際上是什麼樣的? –

+0

'#include #include using namespace std; class mystring:public string { \t }; int main() { \t mystring a,b; \t cout << a

1

調用基類operawtor很容易,如果你認識到這僅僅是一個有趣的名字功能:

bool operator<(const mystring ms) 
{ 
    //some stmt; 
    //some stmt; 
    return string::operator<(ms); 
} 

唉,不與std::string因爲operator<工作是不是一個成員函數,但是一個免費的功能。喜歡的東西:

namespace std 
{ 
    bool operator<(const string &a, const string &b); 
} 

的基本原理是一樣的,叫滑稽命名函數:

bool operator<(const mystring ms) 
{ 
    //some stmt; 
    //some stmt; 
    operator<(*this, ms); 
} 
+0

'std :: string'沒有'operator <'成員。 –

+0

我試過 錯誤:'operator <'不是'std :: string {aka std :: basic_string }'的成員' –

+0

Ops!你是對的,這是一個免費的功能!不是會員!更正答案... – rodrigo

相關問題