我有这样的代码
#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 [],而不是 string
最佳答案
改为返回对列表的引用
std::array<Account, SIZE> & // << Note the &
User::getListAccount();
或者更好的是,不要暴露内部结构
Account&
User::getUser(size_t n)
{
return listAccount[n];
}
关于C++ - 返回 C++11 std::array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43975140/