C++ 运算符重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/20 20:28:22
#include <iostream>
#include <string>
using namespace std;

class Student
{
public:
Student(string n):name(n){}
friend bool operator ==(Student &stu1, Student &stu2);
private:
string name;
};

bool operator ==(Student &stu1, Student &stu2)
{
return stu1.name == stu2.name;
}

int main()
{
Student stu1("Jinxin");
Student stu2("Jinxin");
if(stu1 == stu2)
cout<<"相等"<<endl;
else
cout<<"不相等"<<endl;
system("pause");
return 0;
}

以上代码在dev C++ 环境中正常编译,可以运行,但是在 Visual C++ 6.0环境编译发生错误,我不知是为什么,提示的错误为:

Compiling...
Cpp1.cpp
F:\myfiles\C++ test\Cpp1.cpp(17) : error C2248: 'name' : cannot access private member declared in class 'Student'
F:\myfiles\C++ test\Cpp1.cpp(11) : see de

问题主要是:
1.在VC6中所提供的不带后缀.h的头文件不支持把成员函数重载为友元函数,所以,友元函数不能够调用类中定义的私有成员。故产生了前两个错误。所以,应该把首行改为#include<iostream.h>,并且把using namespace std;此行去掉,这样,就可以支持友元函数了。
2.因为字符串常量本身就可以比较大小,所以当==的两端是字符串常量时,编译器无法判断这里的==运算符是重载的运算符,还是字符串的运算符。故产生了第三个错误。所以,应该把name定义为char型,然后再用指针进行调用,就不会产生歧义了。

以下是本人改进的程序,希望对你有帮助。

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

class Student
{
public:
Student(char *n):p(n){}
friend bool operator == (Student &, Student &);
private:
char *p;
};

bool operator == (Student &a1, Student &a2)
{
if (strcmp(a1.p , a2.p)==0)
return true;
else
return false;
}

int main()
{
Student stu1("Jinxin");
Student stu2("Jinxin");
if(stu1 == stu2)
cout<<"相等"<<endl;
else
cout<<"不相等"<<endl;
system("pause&qu