您的位置:首页 > 编程语言 > C语言/C++

面试题之 C++输出类对象时导致错误的去处运算符<< 的重载

2014-04-30 19:03 260 查看
今天把去年某公司的笔试题拿出来,做了下,发现了几个问题。如题目所示:程序找错: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.cpp30 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);
[/code]
~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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐