如何返回一个类的两个对象相加的结果

how to return the result of addition of two objects of a class

本文关键字:两个 结果 对象 一个 何返回 返回      更新时间:2023-10-16

编译时,当返回对象添加的结果时,它显示类似于sme error的删除函数constexpr Player::Player(const Player&)的使用。

#include <bits/stdc++.h>
using namespace std;
class Player
{
char* name;
int num;
public:
Player(char* str = nullptr, int n = -1)
: name{str}
, num{n}
{
if (str != nullptr)
{
name = new char[strlen(str) + 1];
strcpy(name, str);
str = nullptr;
}
}
Player& operator=(const Player& temp)
{
delete[] this->name;
this->name = new char[strlen(temp.name) + 1];
strcpy(this->name, temp.name);
this->num = temp.num;
}
Player operator+(const Player& temp);
};
Player Player::operator+(const Player& temp)
{
char* str = new char[strlen(name) + strlen(temp.name) + 1];
strcpy(str, name);
strcat(str, temp.name);
int n = num + temp.num;
Player result{str, n};
delete[] str;
return result;
}
int main()
{
Player p1{"abc", 11};
Player p2{" xyz", 9};
Player p3;
p3 = p1 + p2;
}

根据C++17标准(12.8复制和移动类对象(

7如果类定义没有显式声明副本构造函数,其中一个是隐式声明的。如果类定义声明移动构造函数或移动赋值运算符隐式声明的复制构造函数被定义为已删除;否则它被定义为默认值(8.4(。如果该类具有用户声明的复制赋值运算符或用户声明的析构函数

此外,移动构造函数被定义为已删除,至少是因为明确定义了复制赋值运算符。

因此,您需要显式定义operator +形成返回对象所需的复制构造函数。

请注意,类定义还有其他缺点。例如,数据成员name可以等于nullptr。这是默认构造函数允许的。在这种情况下,由于以下语句,cppy赋值运算符可以调用未定义的行为

this->name = new char[strlen(temp.name) + 1];
^^^^^^^^^^^^^^^^^

字符串文字具有常量字符数组的类型。因此,默认构造函数的第一个参数应声明为具有const char *类型。