【发布时间】: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