【发布时间】:2017-10-13 23:33:42
【问题描述】:
我有一些类似的代码
#define SIZE 10
Class User
{
public:
std::array<Account, SIZE> getListAccount()
{
return listAccount;
}
private:
std::array<Account, SIZE> listAccount
}
Class Account
{
public:
void setUserName(std::string newUSN)
{
userName=newUSN;
}
private:
string userName;
string password;
}
int main()
{
User xxx(.......);
xxx.getListAccount()[1].setUserName("abc"); // It doesn't effect
return 0;
}
为什么 main 中的 setUserName() 函数调用不更改我的 xxx 用户中的名称?
顺便说一句:
- 我正在使用
std::array,因为我想将数据保存在二进制文件中 - 在我的实际代码中,我使用的是 char [],而不是字符串
【问题讨论】:
-
您的 getter 返回数组的副本,因此名称只是在副本中更改,而不是在原始中。
-
你需要问一个具体的问题,从表述上看你真正想要的是什么。绝对不想返回数组或对它的引用。
-
您粘贴了无效的 C++ 代码:
class必须全部小写,并且您需要在std::array<Account, SIZE>中使用之前定义class Account,并且您错过了三个;-- 请阅读如何提供minimal reproducible example!此外,为了减少名称污染,请避免使用#define。而是声明static const size_t SIZE=10;或enum {SIZE=10};(甚至可以在要使用它的类中完成)。
标签: c++ arrays c++11 reference