今天把去年某公司的笔试题拿出来,做了下,发现了几个问题。
如题目所示:
程序找错:cout<<str; 当str为一个类的对象,
(1)调试环境为VC++6.0时报:
'<<' : no operator defined which takes a right-hand operand of type 'class Str' (or there is no acceptable conversion)
(2)调试环境为Vs2010时报:
错误 2 error C2679: 二进制“<<”: 没有找到接受“Str”类型的右操作数的运算符(或没有可接受的转换) d:\web\vs2010test\finderrorruijienetwork\finderrorruijienetwork\finderrorruijienetwork.cpp 30 1 FindErrorRuiJieNetwork
源程序如下:
#include <iostream>
#include <string>
using namespace std;
class Str{
public:
Str(char* s)
{
buf = new char[strlen(s)];
strcpy(buf,s);
}
//添加<<的重载
friend
ostream& operator << (ostream& out, Str& str);
~Str()
{
delete buf;
}
private:
char *buf;
};
int main()
{
Str s="hello world";
Str b=s;
cout<<b<<endl; //出错行,初步认为是操作符<<的重载问题
return 0;
}
发帖求助的地址为:http://bbs.csdn.net/topics/390770600?page=1#post-397300319