C++关于友元函数的问题
来源:百度知道 编辑:UC知道 时间:2024/06/19 03:05:48
重载输出操作符,设置为友元,但是编译时出错,提示是不能访问私有对象S,还有<<操作符是ambiguous
#include<iostream>
#include<string>
using namespace std;
class Test
{
friend ostream& operator<<(ostream &os, const Test &t);
public:
Test(const string& str = " "):s(str){}
private:
string s;
};
ostream& operator<<(ostream &os,const Test &t)
{
os<<t.s;//这里出错,不能访问私有成员S
return os;
}
int main()
{
Test t("fuck!");
cout<<t;//operator<< is ambiguous
return 0;
}
高手帮忙看看问题出在哪里,谢谢
真的是VC6.0编译器的问题吗?难道这个编译器有问题?
#include<iostream>
#include<string>
using namespace std;
class Test
{
friend ostream& operator<<(ostream &os, const Test &t);
public:
Test(const string& str = " "):s(str){}
private:
string s;
};
ostream& operator<<(ostream &os,const Test &t)
{
os<<t.s;//这里出错,不能访问私有成员S
return os;
}
int main()
{
Test t("fuck!");
cout<<t;//operator<< is ambiguous
return 0;
}
高手帮忙看看问题出在哪里,谢谢
真的是VC6.0编译器的问题吗?难道这个编译器有问题?
#include <iostream>
#include <string>
using namespace std;
class Test
{
public:
Test(const string& str = " "):s(str){}
friend ostream& operator<<(ostream &os, const Test &t)
{
os<<t.s<<endl;//这里出错,不能访问私有成员S
return os;
}
public:
string s;
};
int main()
{
Test t("fuck!");
cout<<t;//operator<< is ambiguous
return 0;
}
vc6好像有bug,,这样就对了
老问题了,,据说下个sp6补丁装上就好了!
应该在第4行处加类的声明 和函数声明
using namespace std;
class Test;
ostream& operator<<(ostream &os,const Text &t);
原本应该在类前声明函数 但参数中又有类 所以在函数声明的前边加个类的声明
C++默认下是私有的,所以楼主定义的友元由于没有声明公有,所以该友元外部不能访问,应该把public这句移到友元的前面。
我在VC7.1编译没有错误哦,正确打印fuck!