使用向量push_back一个类对象。

时间:2017-11-06 17:30:37

标签: c++ vector

如何在另一个类中向vector添加类的对象。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class info{
    private: 
        int id;
        string name;
    public:
        info(int extId, string extName) {
            this->id = extId;
            this->name = extName;
        }
};

class db {
    private:
        vector<info> infoVector;
    public:
        void pushData(info * data) {
            this->infoVector.push_back(&data);
        }
};

int main(){ 
    info * testData = new info(123, "nice"); 

    db database;
    database.pushData(testData);    

    return 0;
}

我正在创建info类的对象。该对象包含一个int和一个string变量。然后我创建了db对象,我在那里传递了一个testData对象。

我在构建项目时收到错误消息。

main.cpp: In member function ‘void db::pushData(info*)’:
main.cpp:23:44: error: no matching function for call to ‘std::vector<info>::push_back(info*&)’
             this->infoVector.push_back(data);
                                            ^
In file included from /usr/include/c++/5/vector:64:0,
                 from main.cpp:2:
/usr/include/c++/5/bits/stl_vector.h:913:7: note: candidate: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = info; _Alloc = std::allocator<info>; std::vector<_Tp, _Alloc>::value_type = info]
       push_back(const value_type& __x)
       ^
/usr/include/c++/5/bits/stl_vector.h:913:7: note:   no known conversion for argument 1 from ‘info*’ to ‘const value_type& {aka const info&}’

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您似乎试图将info *类型的地址传递给vector<info>::push_backonly accepts types of const info & or info &&。致电push_back时,请尝试使用dereference operator * instead of the address-of operator &

this->infoVector.push_back(*data);

然而,这不是一种使用指针的好方法,如果从向量中删除data或删除它,可能会导致内存泄漏或段错误。 vector最好拥有其成员,因此您可以考虑改为:

class db {
    private:
    vector<info> infoVector;
    public:
    void pushData(info data) {            // note: not a pointer
        this->infoVector.push_back(data); // note: not address-of
    }
};

int main(){ 
    info testData(123, "nice"); // note: not a pointer
    db database;
    database.pushData(testData);
    return 0;
}

否则,如果您真的希望infoVector包含指针,请将其声明为:

std::vector<info*> infoVector;

然后删除address-to运算符。

P.S。,avoid using namespace std whenever possible

答案 1 :(得分:-1)

您有vector<info>,并且想要info *,请尝试:

int main(){ 
    info testData(123, "nice"); 

    db database;
    database.pushData(testData);    

   return 0;
}