新微赢技术网

标题: 很不明白的问题 [打印本页]

作者: 绝不放弃    时间: 2009-11-4 02:22
标题: 很不明白的问题
#include <iostream>
#include <string>
using namespace std;
class String
{
private:
string s;

public:

String(string s1)
{
s=s1;
}
String()
{
}
~String()
{

}

void show()
{
cout<<s<<endl;
}

String operator+(String &);
friend void operator=(String &,String &);
friend int operator>(String &,String &);

};
String String::operator+(String &s1)
{
String t;
t.s=s1.s;
return t;
}


void operator=(String &s1,String &s2)
{
s1.s=s2.s;

}

int operator>(String &s1,String &s2)
{
if(s1.s>s2.s)
return 1;
else
return 0;
}


int main()
{
String str1("LOVE"),str2("you"),str3;
str1.show();
str2.show();
str3=str1+str2;
str3.show();
if(str1>str2)
cout<<"str1>str2"<<endl;
else
cout<<"str1<str2"<<endl;
getchar();
return 0;
}

出错:
32 D:\Dev-Cpp\未命名1.cpp
`void operator=(String&, String&)' must be a nonstatic member
47 D:\Dev-Cpp\未命名1.cpp
`void operator=(String&, String&)' must be a nonstatic member
作者: 最ヅ后愛上你    时间: 2009-11-4 02:22
opertor=必需是成员函数
以下是MSDN中对此的描述
The assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:

●It must be a nonstatic member function. No operator= can be declared as a nonmember function.

●It is not inherited by derived classes.

●A default operator= function can be generated by the compiler for class types if none exists.
作者: 风忠人    时间: 2009-11-4 02:22
这题是书上后面的练习题
规定"=,>"运算符重载函数为友元函数,而“+”为运算符重载函数为成员函数
楼上的,可以用中文解释么?我英语太烂了
作者: DJ敗類ヤ傲天    时间: 2009-11-4 02:22
严格的说,赋值操作符是一个二元操作符.它的声明和其他的二元操作符一样,但是以下例外

●赋值操作符必需是非静态成员函数.opertor=不可以声明为非成员函数

●赋值操作符不会被派生类继承

●如果编译器找不到opertor=,就会为类生成一个缺省的opertor=函数

以上是我的翻译,不太准确。

如果书上非让你那么做,换本书吧
作者: 欧阳天明    时间: 2009-11-4 02:22
那本书,本来就是入门者学的,我也觉得垃圾,
不过,我只想把后面的练习全部做完,

谢谢!你噢
作者: 哪里找    时间: 2009-11-4 02:22
你写的那程序也太离谱了吧,,,
作者: 魅力ぉ小猪ぎ    时间: 2009-11-4 02:22
楼上的``指教一下啊
作者: 依ing梦    时间: 2009-11-4 02:22
友员重载等号的参数要是常类型
作者: 落叶秋雨    时间: 2009-11-4 02:22
The assignment operator (=) is, strictly speaking, a binary operator. Its declaration is identical to any other binary operator, with the following exceptions:
●It must be a nonstatic member function. No operator= can be declared as a nonmember function.
●It is not inherited by derived classes.
●A default operator= function can be generated by the compiler for class types if none exists.

这里面清楚的讲到:"No operator= can be declared as a nonmember function",即等于号的重载函数必须是(类)的成员函数。而你的程序里把它作为了友元函数,不符合语法要求。




欢迎光临 新微赢技术网 (http://bbs.weiying.cn/) Powered by Discuz! X3.2