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

友元函数不能访问类的私有成员?

hxyzlhx 发布于 2008-04-11 14:22, 793 次点击
以下代码在编译时通不过,显示很多错误,我将错误信息放在代码的注示中了,请各位高手给珍断珍断,谢谢!
#include <iostream>
#include <string>
using namespace std;

class String
{public:
   String(){p=NULL;}
   String(char *str);
   friend bool operator>(String &st1,String &st2);
   void display();
private: char *p;//错误2:see declaration of 'p'
};

String::String(char *str)
{p=str;}

void String::display()
{cout<<p;}

bool operator>(String &st1,String &st2)
{if(strcmp(st1.p,st2.p)>0) //错误1:error C2248: 'p' : cannot access private
 // member declared in class 'String'
    return true;
  else return false;
 }

int main()
{String st1("Hello"),st2("Book")
  cout<<(st1>st2)<<endl;
  return 0;
}
2 回复
#2
sunkaidong2008-04-11 14:33
#include <iostream>
#include <string>
using namespace std;
namespace a{
class String
{
public:
   String(){p=NULL;}
   String(char *str);
   friend bool operator>(String &st1,String &st2);
   void display();
private:
    char *p;
};

String::String(char *str)
{
    p=str;
}

void String::display()
{
    cout<<p;
}

bool operator>(String &st1,String &st2)
{
    if(strcmp(st1.p,st2.p)>0)

    return true;

     else

      return false;
}
}
int main()
{
    a::String st1("Hello"),st2("Book");
  cout<<(st1>st2)<<endl;
  return 0;
}
#3
sunkaidong2008-04-11 14:36
不是你的问题..是编译器自己问题..你加命名空间隔开空间污染吧..
1