示例:
题目:输入两学生成绩,求和。
1.0代码:通过对运算符“+”的类方法重载,实现两学生成绩的求和。
#include<iostream>
using namespace std;
class Student
{
public:
void setData(string n, int a, double s);
Student operator+(const Student &a) const;
void show(void);
private:
string name;
int age;
double score;
};
void Student::setData(string n, int a, double s)
{
name = n;
age = a;
score = s;
}
Student Student::operator+(const Student &a) const
{
Student temp;
temp.score = a.score + this->score;
return temp;
}
void Student::show(void)
{
cout << score << endl;
}
int main(void)
{
Student a, b;
string name;
int age;
double score;
cout << "Enter the name of a: ";
cin >> name;
cout << endl << "Enter the age of a: ";
cin >> age;
cout << endl << "Enter the score of a: ";
cin >> score;
a.setData(name, age, score);
cout << "Enter the name of b: ";
cin >> name;
cout << endl << "Enter the age of b: ";
cin >> age;
cout << endl << "Enter the score of b: ";
cin >> score;
b.setData(name, age, score);
//用法一:
Student c = a.operator+(b);
cout << "The score of a+b is ";
c.show();
//用法二:
Student d = a + b;
cout << "The score of a+b is ";
d.show();
return 0;
}
2.0代码:在1.0基础上,通过对运算符“<<”的重载提高了程序输出的简易性,并与普通show()方法进行对比。
#include<iostream>
using namespace std;
class Student
{
public:
void setData(string name, int age, double score);
Student operator+ (const Student& a) const;
void show(void);
friend void operator<< (ostream &os, const Student &a);
private:
string name;
int age;
double score;
};
void Student::setData(string n, int a, double s)
{
name = n;
age = a;
score = s;
}
Student Student::operator+ (const Student& a) const
{
Student temp;
temp.name = name + a.name;
temp.age = age + a.age;
temp.score = score + a.score;
return temp;
}
void Student::show(void)
{
cout << "name :\t" << name << endl;
cout << "age :\t" << age << endl;
cout << "score :\t" << score << endl;
}
void operator<< (ostream &os, const Student &a)
{
os << "name :\t" << a.name << endl;
os << "age :\t" << a.age << endl;
os << "score:\t" << a.score << endl;
}
int main(void)
{
Student a, b, c;
string name;
int age;
double score;
cout << "Enter the name 、 age and score of a:";
cin >> name >> age >> score;
a.setData(name, age, score);
cout << "Enter the name 、 age and score of b:";
cin >> name >> age >> score;
b.setData(name, age, score);
c = a.operator+(b);
cout << "类方法打印 Student 的有关信息:" << endl;
a.show();
b.show();
c.show();
cout << "友元函数打印 Student 的有关信息:" << endl;
cout << a;
cout << b;
cout << c;
return 0;
}
坑:
1.0:
- 类的私有数据成员在main函数中无法直接通过对象进行访问,需要通过公有类方法进行(例setData()、show());
- operator关键字进行运算符重载时,对非友元函数一般双目运算符只有一个参数,另一参数可直接调用或借助this指针;而友元函数为两个参数。
2.0:
- 友元函数在类中声明时要标注friend关键字,但在进行实现时,由于不是类方法故不需支出函数的命名空间。并由此可得出友元函数不属于类方法但可实现对类私有数据成员的访问。