我不能将两个用户定义的类声明变量设置为彼此相等?
I can't set two user-defined class declared variables equal to each other?
所以我正在描述c++课程中计算机科学基础的输出,并且指示要求我复制并粘贴以下代码到我的编译器中:
#include <iostream>
#include <string>
using namespace std;
struct student_record
{
string firstname, lastname;
double age, income;
int number_of_children;
char sex;
};
int main()
{
student_record Mary;
student_record Susan;
cout<<"Enter the firstname and lastname: ";
cin>>Mary.firstname;
cin>>Mary.lastname;
cout<<"Enter age: ";
cin>>Mary.age;
cout<<"Enter income: ";
cin>>Mary.income;
cout<<"Enter number of children: ";
cin>>Mary.number_of_children;
cout<<"Enter sex: ";
cin>>Mary.sex;
Susan = Mary;
if (Susan == Mary)// I get the error here: Invalid operands to binary expression('student_record' and 'student_record')
{
cout<<Susan.firstname<<" "<<Mary.lastname<<endl;
cout<<Susan.age<<endl;
cout<<Susan.income<<endl;
cout<<Susan.number_of_children<<endl;
cout<<Susan.sex<<endl;
}
return 0;
}
我不太明白问题出在哪里,因为两者是同一类型的,而且"Susan = Mary;"这一行也没有给出错误。此外,这个程序的问题在我的实验室没有使它看起来好像我应该得到一个错误,所以我很困惑。谢谢你的帮助。
您需要提供比较操作符:
struct student_record
{
string firstname, lastname;
double age, income;
int number_of_children;
char sex;
//operator declaration
bool operator==(student_record const& other) const;
};
//operator definition
bool student_record::operator==(student_record const& other) const
{
return (this->firstname == other.firstname &&
this->lastname == other.lastname &&
this->sex == other.sex); //you can compare other members if needed
}
c++为类提供了默认构造函数、复制构造函数、赋值操作符(此处使用)和移动构造函数/赋值操作。
不管怎样,它不会生成operator==,所以你必须自己做(查找operator重载)。
检查这个问题背后的原因,并进一步参考
相关文章:
- 设置变量时C++程序挂起
- 从系统("command") (C++) 设置变量
- 在构造函数中设置变量失败?
- 如何为输入设置变量编号和__android_log_print格式
- 从输入文件 c++ 中提取和设置变量
- 使用 void 函数在主函数中设置变量的值
- 未在另一个函数中设置变量引用的问题
- 对于循环设置变量为条件
- 使用 argv 设置变量
- 为什么我的代码未设置变量
- 在C++中设置变量的值之前检查变量是否更好
- 在 if 语句中设置变量
- 在子类中设置变量
- 未设置变量并返回异常数字
- 如何设置变量的 char 数组的元素数量
- C++指针运行时错误 - 使用指针设置变量然后检索
- 从C++设置变量时 QML 内存泄漏
- 使用此功能在构造函数中设置变量
- 从函数设置变量时不会更改
- 类中的二传手不会设置变量