【问题标题】:how to return the result of addition of two objects of a class如何返回一个类的两个对象相加的结果
【发布时间】:2020-07-13 15:07:17
【问题描述】:

在编译时显示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++ class copy-constructor deleted-functions default-copy-constructor


【解决方案1】:

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

7 如果类定义没有显式声明一个副本 构造函数,一个是隐式声明的。如果类定义 声明一个移动构造函数或移动赋值运算符, 隐式声明的复制构造函数被定义为已删除;除此以外, 它被定义为默认值(8.4)。 不推荐使用后一种情况,如果 该类具有用户声明的复制赋值运算符或 用户声明的析构函数。

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    相关资源
    最近更新 更多