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

时间:2021-04-02 16:58:00

I have created my own Vector and Array classes which I have tested and work fine. However, in the following code I am having problems accessing the methods in an AccountInfo class. _accounts is declared like this:

我已经创建了自己的Vector和Array类,我已经测试并且工作正常。但是,在以下代码中,我在访问AccountInfo类中的方法时遇到问题。 _accounts声明如下:

Vector<AccountInfo*> _accounts[200]; // store up to 200 accounts

Before, _accounts was only of type AccountInfo. After switching to a vector, every instance that uses _accounts has the error: Expression must have pointer type.

之前,_accounts只是AccountInfo类型。切换到向量后,使用_accounts的每个实例都有错误:Expression必须具有指针类型。

Here is my code:

这是我的代码:

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++;
        }
    }

Is there a way to access the AccountInfo methods from the variable _accounts?

有没有办法从变量_accounts访问AccountInfo方法?

1 个解决方案

#1


1  

You defined an array of vectors with:

您定义了一个向量数组:

Vector<AccountInfo*> _accounts[200]; // store up to 200 accounts

This is not the same as declaring a single vector with a capcity of 200. If you were using a standard vector then it would look like:

这与声明一个容量为200的单个向量不同。如果您使用的是标准向量,那么它看起来像:

std::vector<AccountInfo*> _accounts(200); // store up to 200 accounts

#1


1  

You defined an array of vectors with:

您定义了一个向量数组:

Vector<AccountInfo*> _accounts[200]; // store up to 200 accounts

This is not the same as declaring a single vector with a capcity of 200. If you were using a standard vector then it would look like:

这与声明一个容量为200的单个向量不同。如果您使用的是标准向量,那么它看起来像:

std::vector<AccountInfo*> _accounts(200); // store up to 200 accounts