指向对象的指针向量,无法访问对象数据字段。(表达式必须具有指针类型)
Vector of pointers pointing to object, can't access object data fields. (expression must have pointer type)
我已经创建了自己的Vector和Array类,经过测试,它们运行良好。但是,在下面的代码中,我在访问AccountInfo类中的方法时遇到了问题。_账户是这样声明的:
Vector<AccountInfo*> _accounts[200]; // store up to 200 accounts
以前,_accounts的类型仅为AccountInfo。切换到向量后,每个使用_accounts的实例都会出现错误:表达式必须具有指针类型。
这是我的代码:
ostream& operator << (ostream& s, UserDB& A){
// print users
for (unsigned int i = 0; i < A._size; i++){
//print name
s << A._accounts[i]->getName() << endl;
}
return s; // return the statement
}
//---------------------------------------------------------------------------- --------------------
//Destructor of UserDB
UserDB::~UserDB(){
for (int i = 0; i < _size; i++){
delete[] _accounts[i]; // delete objects in _accounts
}
}
//------------------------------------------------------------------------------------------------
// add a new user to _accounts
void UserDB::adduser(AccountInfo* newUser){
_accounts[_size] = newUser;
_size++; //increment _size.
if (newUser->getUID() > 0){
//print if UID has a value
cout << newUser->getName() << " with " << newUser->getUID() << " is added." << endl;
}
else {
newUser->setUID(_nextUid); //automatically set UID for user if empty
cout << newUser->getName() << " with " << newUser->getUID() << " is added." << endl;
_nextUid++;
}
}
有没有办法从变量_accounts访问AccountInfo方法?
您用定义了一个向量数组
Vector<AccountInfo*> _accounts[200]; // store up to 200 accounts
这与声明capcity为200的单个向量不同。如果你使用的是标准矢量,那么它看起来像:
std::vector<AccountInfo*> _accounts(200); // store up to 200 accounts
相关文章:
- 为什么指针对象没有调用默认构造函数
- 如何访问双指针对象中的方法
- 如何使用智能指针对象执行成员函数指针
- 调用带有指针对象错误的指针变量
- 如何从模板类重载创建的指针对象上的运算符?
- C++指针对象的运算符重载
- 如何初始化数组指针对象
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- C++指针对象差异
- 涉及继承,指针对象的交易以及何时进行的问题
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 字符指针对象和相应的字符数组元素比较
- 如何在 c++ 中克隆为弱指针对象
- 指针对象使用CPP中的指针表达式进行比较
- Visual Studio中智能指针对象的自定义视图
- 使用指针 /对象 /模板参数正确构成
- 如果我确定只有一个线程一次处理指针/对象,则C/C 仍应使用同步
- 如何将值分配给指针对象 c++
- 更改智能指针对象,然后访问它