#include <iostream>
using namespace std;
class students {
public:
students(); //default constructor
students(const students & s1); //copy constructor
void setScore(double p) { score = p; } //score setter
students operator+(const students & s2) const; //define students + students
private:
double score; //the score variable
};
int main() {
cout << "omidh object ";
students omidh;
cout << "negin object ";
students negin;
negin.setScore(2.0);
omidh.setScore(3.0);
cout << "total object ";
students total = omidh + negin;
}
students students::operator+(const students & s2) const {
cout << "s3 object ";
students s3;
s3.score = score + s2.score;
return s3;
}
students::students() {
cout << " used default constructor\n";
}
students::students(const students & s1) {
cout << " used copy constructor\n";
}
这是一个简单的类,对象“omidh”,“negin”和“s3”调用了默认构造函数,但我不知道构造函数做什么“total”调用。它应该调用一个拷贝构造函数,因为我返回了一个学生对象作为操作符重载的返回类型。但它工作正常并将s3分配给总数。
节目输出:
omidh对象使用默认构造函数
negin对象使用默认构造函数
总对象s3对象使用默认构造函数