重载C++运算符以将对象中的指针设置为其他对象



对于编程任务,我需要创建一个使用类、对象和运算符重载将两个人"结合"在一起的程序。这是我的:

#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;
}

当我用&amp;,它两次都返回0。当它试图打印配偶的名字时(F.配偶->名字(,我会得到一个segfault。我在指针方面非常缺乏经验,但我有理由相信问题出在&操作人员我只是不确定出了什么问题。

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;
}

您正在设置从已发送参数复制到参数的对象。

#include <iostream>
class Family {
public:
Family() {
std::cout << "default ctorn";
}
Family(const Family &) {
std::cout << "copy ctorn";
}
};
void foo(Family a) {
std::cout << "address of parameter " << &a << "n";
}
int main() {
Family f;
std::cout << "address of real object " << &f << "n";
foo(f);
}

它输出

default ctor
address of real object 0x7ffee1255928
copy ctor
address of parameter 0x7ffee1255920

正如你所看到的,这些是不同的物体。已使用创建第一个族对象

Family f;

之后,我们编写f地址的地址,当我们作为参数发送给foo函数时,作为该对象的参数。我们可以看到复制ctor正在工作。

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;
}

您应该使用L值引用来设置此对象。

最新更新