Vector pointers and passing objects by reference i

2019-09-07 06:07发布

问题:

I have the following class:

class Database
{
private:
    vector<myObject*> m_vectorObj;

public: 
    void addObject(myObject &passObj)
}

I'm trying to do this:

void Database::addObject (myObject &passObj)
{
    m_vectorObj.push_back(passObj);
}

But is giving me the error "No matching function to call", how can I make this work and pass the object and store the pointer ?

回答1:

First of all, ask yourself if you really need to use pointers

If you do, then you have 2 options.

1: You are just missing & before passObj

m_vectorObj.push_back(&passObj);
                      ^

2: Change your function (from reference to pointer)

void Database:addObject (myObject *passObj)//pointer to myObject instead of reference
{
    m_vectorObj.push_back(passObj);
}

I wouldn't use pointers at all, but i suggest you to encapsulate'em into std::unique_ptr



回答2:

you are passing a reference to a pointer type, which does not equal any prototype call you have.

If you want to add pointers change your code to accept pointer objects:

void Database::addObject (myObject * passObj)
{
   m_vectorObj.push_back(passObj);
}

//somewhere:
Database db;
db.addObject(new myObject);

note that references are usually ment for modyfiing the passed arguments



回答3:

Scope resolution operator is '::' not ':'. Change void DataBase:addObject to DataBase::addObject.