【问题标题】:Copy constructor should copy *string values复制构造函数应该复制 *string 值
【发布时间】:2014-05-18 05:21:30
【问题描述】:

我有一堂课:

class BankAccount
{
    string *name;
    string *number;
public:
    BankAccount(BankAccount &);
    ~BankAccount();
};

BankAccount::BankAccount(BankAccount &account)
{
    string nameS = account.name;
    this->name = new string(nameS);
    this->number = new string(account.*number);
}

我希望我的复制构造函数将字符串(不是指针,而是指针指向的字符串)复制到新对象。我尝试了两种不同的方法,但从未成功。

编译器消息:

conversion from 'std::string* {aka std::basic_string<char>*}' to non-scalar type 'std::string {aka std::basic_string<char>}' requested

'((BankAccount*)this)->BankAccount::number' cannot be used as a member pointer, since it is of type 'std::string* {aka std::basic_string<char>*}'

【问题讨论】:

  • 这个类的设计太疯狂了。不要使用指针或new,只要有string 成员即可。
  • 只使用 std::string 成员有什么问题?如果你这样做了,代码中的所有问题都会消失。
  • string nameS = *(account.name);this->number = new string(*(account.number));
  • @pw94 - 你的班级没有赋值运算符。即使使用 sgar91 给您的更改,我也可以使用 2 行 main() 程序轻松打破它。鉴于它很容易被破坏,你学到了什么?如何制作损坏的程序?您应该制作工作 C++ 程序,而不是有缺陷的程序。使用 std::string 删除 all 您看到的错误。这就是为什么这些作业如果没有在课堂上给予适当的讨论时间,反而是学习 C++ 的障碍而不是帮助。你创建了错误的程序,同时认为这些程序是“好”的。
  • 为什么不只存储字符串(而不是指针)或者使用自动指针而不是经典指针?顺便说一句,复制构造函数不应该接受 const 引用吗? (原本是一个答案……)

标签: c++ string copy-constructor dynamic-memory-allocation


【解决方案1】:

BankAccount 类应该只包含字符串对象而不是指向字符串的指针

class BankAccount
{
    string name;
    string number;
};

编辑:正如其他用户所指出的,您现在不再需要编写复制构造函数或析构函数,因为 std 字符串会自行处理

【讨论】:

  • 复制构造函数实际上应该是这样的:
  • 即,因为成员是自己处理的类,所以不需要复制构造函数(或析构函数)
  • @juanchopanza 我不同意。当前示例是在构造函数内部使用赋值,而不是使用构造函数的初始化列表。在C++ FAQ 上有一些关于此的信息。除此之外,TooTone 是对的,在这种情况下甚至不需要复制构造函数。
  • 改为使用初始化列表。
  • @ParvusM 的重点是当包含string 对象时不需要复制构造函数。析构函数也不是。 (juanchopanza 的评论表明复制构造函数应该看起来像“”,即它不应该存在。)
【解决方案2】:

根据其他 cmets 和答案,在这种情况下,不需要使用指针作为实例变量。最好将实例变量设为实际字符串。但只是为了解释你的问题:

string nameS = account.name;

account.name 是一个指向字符串的指针,所以你需要这个:

string nameS = *account.name;

在此声明中:

this->number = new string(account.*number);

您的解引用不正确。应该是:

this->number = new string(*account.number);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2012-01-02
    • 2013-10-13
    相关资源
    最近更新 更多