C++ - 返回 C++11 std::array

标签 c++ arrays c++11 reference

我有这样的代码

#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/

相关文章:

c++ - boost::lock 在 boost 1.53 中无法编译

c++ - 如何在 C++ 中创建具有子函数的对象?

c++ - 在 C++ 中比较 char 数组的值

c++ - 如何从其他类访问不同类中的变量

c++ - Multimap 使用 std::make_pair 与 std::pair 构造函数插入键类型信息

c++ - 基于 : issue with constness 范围内的自定义迭代器

c++ - fftw3 for poisson with dirichlet boundary condition for all side of computational domain

c++ - 为什么我不能将两个不同的比较器传递给一个模板函数?

c# - 使用扩展方法复制数组

c# - 数组复制在循环中失败