使用指针使用矢量对象的函数

Use the functions of a vector objects using a pointer

本文关键字:函数 对象 指针      更新时间:2023-10-16

1(.为什么我会收到此错误?正确的语法是什么?

2(.有没有办法在不使用库"vector"的情况下编写相同的代码?

#include <vector>
myClass()
{
    public:
        myClass(int x,int y);
        void doThis()
        {
            //Something
        }
}
int main(void)
{
    std::vector<myClass>*ex_vector = new std::vector<myClass(5,myClass{10,10});
    ex_vector[0]->doThis(); //Error Here
    delete []ex_vector;
}

我收到此错误:

error: base operand of '->' has non-pointer type 'std::vector<myClass>'

正确的语法是

(*ex_vector)[0].doThis();

此外,您应该delete ex_vector;而不是delete[] ex_vector;因为new的类型不是原始数组类型。

但是,很少有充分的理由new std::vector。 只需使用普通对象。