2014-02-12 131 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

相关问题