关于友元函数的一道题

来源:百度知道 编辑:UC知道 时间:2024/05/31 17:19:29
#include <iostream>
using namespace std;

class String
{
public:
String(char *x=NULL):
a(x){}

friend bool operator > (String &y,String &x);
friend bool operator < (String &y,String &x);
friend bool operator == (String &y,String &x);
private:
char *a;
};

int main()
{
String s1("ednadcirgdc"),s2("ednadcirgdc");

if((operator > (String &y,String &x))>0)
cout << "larger" << endl;
if((operator < (String &y,String &x))>0)
cout << "smaller" << endl;
if((operator == (String &y,String &x))>0)
cout << "equal" << endl;

return 0;
}

bool operator > (String &y,String &x)
{
if(strcmp(y.a,x.a)>0)
return true;
else
return false;
}

bool operator < (String &y,String

看来你对运算符重载的使用不太了解,C++中运算符重载函数虽然和一个函数定义的过程一样,但使用的时候却不太像函数调用的样子,而是和一般的算术运算或逻辑运算的使用方式一样。将下面的语句:
if((operator > (String &y,String &x))>0)
cout << "larger" << endl;
if((operator < (String &y,String &x))>0)
cout << "smaller" << endl;
if((operator == (String &y,String &x))>0)
cout << "equal" << endl;
改为:
if (s1 > s2)
cout << "larger" << endl;
if (s1 < s2)
cout << "smaller" << endl;
if (s1 == s2)
cout << "equal" << endl;

楼上的 是OK的,害我没的说了
楼主还是在看看书吧,注意operator重载了
我们只要直接使用就可以了,就像我们平时使用+,-,*,/一样

#include <iostream>
using namespace std;

class String
{
public:
String(char *x=NULL):
a(x){}

friend bool operator > (String &y,String &x);
friend bool ope