如何返回一个类的两个对象相加的结果
how to return the result of addition of two objects of a class
编译时,当返回对象添加的结果时,它显示类似于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 *
类型。
相关文章:
- 如何返回一个类的两个对象相加的结果
- 你好。。。id_public变量不应该给出结果为 81 和 86 吗?为什么它为两个派生类占用不同的内存位置?
- 这两个代码片段相似,但显示的结果不同
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- 为什么 Clang 和 GCC 中两个无符号整数之和的结果类型不同
- 我有两棵二叉树.我想在不更改输入树的情况下深度复制两个二叉树的结果
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 为什么这两个相似的代码计算行列式的结果不同?
- 如何通过键和值以及在C 中的结果映射中比较两个地图?我们有任何STL API吗?
- 如何乘以两个值并原子存储结果
- *char数组到字符串(两次运行代码和两个不同的结果)
- 运算符的两个不同结果 - 在 c++11 中
- 在发布版本中划分两个双精度的结果错误
- 两个结果的std :: chrono :: high_resolution_clock :: now()给出了〜270n
- C++:两个单独的函数在嵌套时返回不同的结果?
- 警告:用两个参数构造函数返回对象时,表达结果未使用
- 随机洗牌似乎会产生相同的结果,但仅在前两个实例中产生相同的结果.我如何避免这种情况
- 运算符*=来自两个实例(矩阵),结果不好
- 在 GCC 4.6 和 4.7 上模板模板扣除的两个不同结果
- 在将两个结果行写入文件之前比较用fprintf生成的结果行