【发布时间】:2020-07-22 09:29:35
【问题描述】:
对于编程任务,我需要创建一个程序,该程序使用类、对象和运算符重载将两个人“结合”在一起。 这是我所拥有的:
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Family{
public:
string name;
int age;
//An object pointer of Family to represent a spouse
Family * spouse;
/**
* A constructor that takes 3 arguments
* @param n takes default 'unknown'
* @param a takes default 18
* @param s takes default NULL
*/
Family( string n="Unknown", int a=18, Family * s=NULL){
name=n;
age=a;
spouse=s;
}
friend void operator&(Family a, Family b) { // Marries two family objects
Family A(a.name, a.age, &b);
Family B(b.name, b.age, &a);
a = A;
b = B;
}
friend bool operator&&(Family a, Family b) { // Checks if two Family objects are married
if (a.spouse == &b && b.spouse == &a) {
return 1;
} else {
return 0;
}
}
};
int main(int argc, char** argv) {
//Declaring an object F using a name and age=18 representing a female.
Family F("Nicky",18);
//Declaring an object M using a name, age =19 and spouse being the previous object
Family M("Nick",19,&F);
//1pt Check if they are married or not using the operator &&
cout << "Are they married " << (F&&M) << endl;
//1pt Marry them to each other using the operator &
(F & M);
//1pt Check if they are married or not using &&
cout << "Are they married " << (F&&M) << endl;
// Printing the spouse of the Female
cout<< "The spouse of female "<< F.spouse->name<<endl;
// Printing the spouse of the male
cout<< "The spouse of male "<< M.spouse->name<<endl;
return 0;
}
当我使用 && 检查他们是否已结婚时,两次都返回 0。当它试图打印配偶的名字(F.spouse->name)时,我得到一个段错误。我对指针非常缺乏经验,但我有理由确定问题出在 & 运算符中。我只是不确定出了什么问题。
【问题讨论】:
-
void operator&(Family a, Family b)应该通过引用来获取它的参数,因为你想改变它们。 -
然后它不应该创建新对象。顺便说一句,
Family不是一个家庭成员的最佳名字。名字很重要 -
和
operator &&在您检查地址时通过 const 引用。 -
您表示通过接受答案(您已经完成)来回答/解决问题。无需将该信息编辑到问题中。
标签: c++ pointers operator-overloading