-3
string operator + (const string &s, char *lit);

string operator + (const string &s, char *lit)
{
    string temp;
    temp.len = s.len+strlen(lit);
    temp.str = new char[temp.len+1];
    strcpy(temp.str, s.str);
    strcat(tmep.str, lit);
    return temp;
}

这是我的教授给我的示例代码,作为重载字符串类的示例。事情是,当我编译它时,它说

std::string operator+(const string&, char*)’ must take either zero or one argument

我只是想知道为什么它不编译?它只需要一个arg。但不会带两个。谢谢。

4

1 回答 1

3

我猜你的教授的意思是命名空间范围函数(只是普通函数)。

而你碰巧声明了非静态成员函数(我猜在某个名为“blog”的类中)。

operator+在命名空间范围内接受 1 或 2 个参数(二元 operator+ 接受 2 个参数,而一元 operator+ 接受 1 个参数)但作为非静态成员函数(在类范围内)它接受 0 或 1 个参数(因为它已经定义了第一个隐式参数通过这个指针)。

于 2013-05-26T21:14:22.393 回答