注册 登录
编程论坛 C++教室

关于操作符重载的问题

yijing21 发布于 2008-04-07 00:10, 759 次点击
在重载时为什么用#include<iostream>头文件重载<<,>>,==操作符时  明明已经把重载函数申明位友元了,但是在重载函数定义时却不能调用私有成员?把头文件改成#include<iostream.h> 注释掉using namespace std;就可以了呢?  但是在用了#include<iostream.h>后string类又出问题了    请高手指点

#include<iostream>
using namespace std;


class C
{
public:
    C():x(0),y(1){}
    friend ostream &operator << (ostream &,const C &);
private:
    int x;
    int y;
};

ostream &operator << (ostream &out,const C &c1)
{
    out<<c1.x<<" "<<c1.y<<endl;
    return out;
}

int main()
{
    C cc;
    cout<<cc;
    return 0;
}


编译错误
:\program files\microsoft visual studio\myprojects\iostream\io.cpp(17) : error C2248: 'x' : cannot access private member declared in class 'C'
        g:\program files\microsoft visual studio\myprojects\iostream\io.cpp(11) : see declaration of 'x'
g:\program files\microsoft visual studio\myprojects\iostream\io.cpp(17) : error C2248: 'y' : cannot access private member declared in class 'C'
        g:\program files\microsoft visual studio\myprojects\iostream\io.cpp(12) : see declaration of 'y'
g:\program files\microsoft visual studio\myprojects\iostream\io.cpp(24) : error C2593: 'operator <<' is ambiguous


但是头文件改成#include<iostream.h>却可以呢
7 回复
#2
zjl1382008-04-07 07:12
VC6的老问题,以前我也用过。
VC6对标准支持不好。。。。。。。。。。。。
#3
sunkaidong2008-04-07 10:09
用命名空间隔开,避免污染...
#4
yijing212008-04-07 18:55
win32平台不是都用VC6多嘛  真是麻烦哦  谁知道具体解决办法啊
#5
sunkaidong2008-04-07 18:57
#include<iostream>
using namespace std;
namespace a{
class C
{
public:
    C():x(0),y(1){}
    friend ostream &operator << (ostream &,const C &);
private:
    int x;
    int y;
};

ostream &operator << (ostream &out,const C &c1)
{
    out<<c1.x<<" "<<c1.y<<endl;
    return out;
}
}

int main()
{
    a::C cc;
    cout<<cc;
    return 0;
}
#6
yijing212008-04-08 12:12
楼上的可以解决  能说明下namespace a{}的作用嘛  谢谢
#7
sunkaidong2008-04-08 12:21
为了防止自己定义的运算符与std空间里面定义的运算符产生冲突,一般用命名空间隔开,这样就不用冲突了..c#里面命名空间也是这样的..还有java里面的包的概念
#8
zjl1382008-04-08 13:00
[bo]以下是引用 [un]yijing21[/un] 在 2008-4-7 18:55 的发言:[/bo]

win32平台不是都用VC6多嘛  真是麻烦哦  谁知道具体解决办法啊

以现在来看,VC6是有点过时了,最新的VS2008也很好用的。不过编程之灵魂在于算法,至于工具,那就要看个人爱好,用着自已觉得舒服就行。
1