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

     今天把去年某公司的笔试题拿出来,做了下,发现了几个问题。

    如题目所示:
    程序找错: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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值