gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:18:30 25 4
gpt4 key购买 nike

对于编程任务,我需要创建一个使用类,对象和运算符重载将两个人“结婚”的程序。
这是我所拥有的:

#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),我遇到了段错误。我对指针非常缺乏经验,但是我可以肯定地确定问题出在&运算符中。我只是不确定怎么了。

最佳答案

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 ctor\n";
}
Family(const Family &) {
std::cout << "copy ctor\n";
}
};

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值引用来设置此对象。

关于c++ - 重载C++运算符以将对象中的指针设置为其他对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61126621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com