一段非常简单的代码,在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;
}
为什么?哪位碰上过相似的问题?

解决方案 »

  1.   

    It maybe incorrect in statement: cout<<s.str,the str is private member, although operator<< is friend,but it only can access str,not the s.str!
      

  2.   

    听不懂...难道你的意思是
    cout<<str;
    return out;
    ???
    这样更不行了。
      

  3.   

    define a public method to get the str member!!
      

  4.   

    for example:
    #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;
    }
      

  5.   

    ostream& operator<<(ostream& out,String & s)
    {
    cout<<s.str;//把这里的cout改成out就可以了
    return out;
    }
      

  6.   

    我在 VC6 下试了一下,变异和结果都没有问题,??#include <string.h>
    #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;
    }
      

  7.   

    agree In355Hz(好象一条狗) 
    rebuild it ???
      

  8.   

    ostream& operator<<(ostream& out,String & s)
    {
    cout<<s.str;//这里不能使用cout,因为这是对“<<”的重载, 
    return out;
    }
      

  9.   

    我也是的
    在vc下实现不了friend,说不能读取私有成员
    如果照上面phiger(phiger)说的用
    ostream& operator<<(ostream& out,String & s)
    {
    cout<<s.GetStr();
    return out;
    }
    那个getstr()本来就是公有的,当然直接可以用了
    我干吗还要用友元啊。
    用友元就是为了直接读取私有的啊In355Hz(好象一条狗)说编译没问题
    不会吧
    我的怎么也不可以啊
      

  10.   

    改正:cout应改为out(笔误)
    请问大家上述问题是怎么回事啊
      

  11.   

    奇怪的是
    我的现在可以了
    去这看看
    http://expert.csdn.net/Expert/topic/1661/1661544.xml?temp=.5240137