指向对象的指针向量,无法访问对象数据字段。(表达式必须具有指针类型)

Vector of pointers pointing to object, can't access object data fields. (expression must have pointer type)

本文关键字:指针 对象 表达式 类型 数据 向量 访问 字段      更新时间:2023-10-16

我已经创建了自己的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