3366中彩色消砖块下载:系统函数声明为类的友元函数 C++

来源:百度文库 编辑:查人人中国名人网 时间:2024/05/05 01:30:33
#include <iostream>
#include <cstring>
using namespace std;
class String
{
public:
String(char *str):p(str){}
void display()
{cout<<p;}
// friend bool operator> (String &s1,String &s2);
friend strcmp(const char *,const char *);
private:
char *p;
};
/*bool operator> (String &s1,String &s2)
{
if(strcmp(s1.p,s2.p)>0)
return true;
else return false;
}*/
int main()
{
String a("nihao"),b("how do you do");
a.display();
b.display();
// cout<<endl<<(a>b)<<endl;
cout<<strcmp(a.p,b.p)<<endl;
return 0;
}

报错:
Compiling...
string.cpp
H:\C++ practice\string.cpp(27) : error C2248: 'p' : cannot access private member declared in class 'String'
H:\C++ practice\string.cpp(13) : see declaration of 'p'
H:\C++ practice\string.cpp(27) : error C2248: 'p' : cannot access private member declared in class 'String'
H:\C++ practice\string.cpp(13) : see declaration of 'p'
执行 cl.exe 时出错.

这是我写的一个小问题,想将strcmp声明为String类的码元函数,不知该怎样用,还望哪位大侠指点一二!不胜感激!

友元函数只能是普通的全局函数或其他类中的成员函数,strcmp是库函数,不可以定义成友元函数

#include <iostream.h>
#include <string.h>