我有一些这样的代码
#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;
}为什么setUserName()函数不调用main更改我的xxx用户的名称?
顺便问一下:
std::array是因为我想将数据保存在二进制文件中发布于 2017-05-15 09:11:32
返回对列表的引用。
std::array<Account, SIZE> & // << Note the &
User::getListAccount();或者更好,不要暴露内部结构
Account&
User::getUser(size_t n)
{
return listAccount[n];
}发布于 2017-05-15 11:58:31
std::array<Account, SIZE> getListAccount() const {
return listAccount;
}这将返回数组的副本。
std::array<Account, SIZE>& getListAccount() {
return listAccount;
}
std::array<Account, SIZE> const& getListAccount() const {
return listAccount;
}这将返回对数组的引用。
template<class T>
struct span_t {
T* b = 0; T* e = 0;
span_t()=default;
span_t(T* s, T* f):b(s),e(f){}
span_t(T* s, std::size_t l):span_t(s, s+l){}
T* begin() const{ return b; }
T* end() const{ return e; }
T& operator[](std::size_t i)const{ return begin()[i]; }
std::size_t size() const { return end()-begin(); }
bool empty() const { return begin()==end(); }
};
span_t<Account> getListAccount() {
return {listAccount.data(), listAccount.size()};
}
span_t<const Account> getListAccount() const {
return {listAccount.data(), listAccount.size()};
}这将返回一对指针的包装器,这些指针表示连续的帐户范围,而不公开用于存储帐户的底层数据结构。
在这三个中,我会使用span_t。它的开销几乎为零,并且隐藏了客户很少感兴趣的信息。
https://stackoverflow.com/questions/43975140
复制相似问题