- 论坛徽章:
- 1
|
c++函数重载问题讨论!!
原帖由 "albcamus" 发表:
这个应该在书上有讲到的。
“=”和“[]”这两个运算符,其返回值都必须是对对象的引用。因为他们的运算结果可能──而且必须保证可以──作为左值。比方说“+”重载,根本不会有
a+b=c;
这样的赋值语句出现,但是=呢?就有可能:
(a=b)++;
或
a[2]=b;
这样都是允许的。
一时讲不明白,看看书吧 如果不清楚呢就不要讲得让别人以为是真的一样.在哪里看到说=,[]这两个运算符其返回值都必须是对象的引用?
楼主可以把你的编译器,环境写出来,编译错误帖出来,在我的dev-cpp4.9.9下没有问题,只是你的程序不是标准的程序给了两个警告,当然main的返回值我改掉了(这是一个错误)参数为引用还是值类型都不是问题.关键的关键应该是你的string和std::string可能出现重复(我不知道带.h的头文件形式那个C++ string类与C标准头文件string.h是怎么处理的,所以我不确定是否一定是这个问题,所以请给出编译错误).我不喜欢这种非标准的程序:
我改为如下:
- #include <iostream>;
- #include <cstring>;
- using std::cout;
- using std::endl;
- using std::strlen;
- using std::strcpy;
- using std::system;
- class string
- {
- char *ptr;
- public:
- string(char *s)
- {
- ptr=new char[strlen(s)+1];
- strcpy(ptr,s);
- }
- ~string()
- {
- delete ptr;
- }
- void print()
- {
- cout<<ptr<<endl;
- }
- string operator=(const string s )
- {
- if (this==&s) return *this;
- delete ptr;
- ptr=new char[strlen(s.ptr)+1];
- strcpy(ptr,s.ptr);
- return *this;
- }
- };
- int main()
- {
- string p1("chen");
- {
- string p2(" ");
- p2=p1;
- cout<<"p2:"<<endl;
- p2.print();
- }
- cout<<"p1:"<<endl;
- p1.print();
- system("PAUSE");
- }
复制代码 |
|