一段非常简单的代码,在VC6下无法通过总说“无法访问私有成员”(大概是这个意思)。但在.NET下可以通过。
#include<iostream>using namespace std;class String{
public:
friend ostream& operator<<(ostream& out,String& s);
String(const char* str);
private:
char* str;
};String::String(const char* s)
{
str=new char[strlen(s)+1];
memcpy(str,s,strlen(s)+1);
}ostream& operator<<(ostream& out,String & s)
{
cout<<s.str;
return out;
}void main()
{
String s("hello");
cout<<s;
}
为什么?哪位碰上过相似的问题?
#include<iostream>using namespace std;class String{
public:
friend ostream& operator<<(ostream& out,String& s);
String(const char* str);
private:
char* str;
};String::String(const char* s)
{
str=new char[strlen(s)+1];
memcpy(str,s,strlen(s)+1);
}ostream& operator<<(ostream& out,String & s)
{
cout<<s.str;
return out;
}void main()
{
String s("hello");
cout<<s;
}
为什么?哪位碰上过相似的问题?
cout<<str;
return out;
???
这样更不行了。
#include<iostream>using namespace std;class String{
public:
friend ostream& operator<<(ostream& out, String& s);
String(const char* str);
char * GetStr() { return str; }
private:
char* str;
};String::String(const char* s)
{
str=new char[strlen(s)+1];
memcpy(str,s,strlen(s)+1);
}ostream& operator<<(ostream& out,String & s)
{
cout<<s.GetStr();
return out;
}void main()
{
String s("hello");
cout << s;
}
{
cout<<s.str;//把这里的cout改成out就可以了
return out;
}
#include <iostream.h>class String{
public:
friend ostream& operator<<(ostream& out,String& s);
String(const char* str);
private:
char* str;
};String::String(const char* s)
{
str=new char[strlen(s)+1];
memcpy(str,s,strlen(s)+1);
}ostream& operator<<(ostream& out,String & s)
{
out<<s.str;
return out;
}void main()
{
String s("hello");
cout<<s;
}
rebuild it ???
{
cout<<s.str;//这里不能使用cout,因为这是对“<<”的重载,
return out;
}
在vc下实现不了friend,说不能读取私有成员
如果照上面phiger(phiger)说的用
ostream& operator<<(ostream& out,String & s)
{
cout<<s.GetStr();
return out;
}
那个getstr()本来就是公有的,当然直接可以用了
我干吗还要用友元啊。
用友元就是为了直接读取私有的啊In355Hz(好象一条狗)说编译没问题
不会吧
我的怎么也不可以啊
请问大家上述问题是怎么回事啊
我的现在可以了
去这看看
http://expert.csdn.net/Expert/topic/1661/1661544.xml?temp=.5240137