简体   繁体   中英

Can I insert an object by value (copying) from one std::vector to another?

(I realized that it was a copy-paste-mistake in my program. But the reason, why I get exactly that error message could still be interesting for somebody else, therefore, I updated the question.)

I have the following code snippet which copies the elements of one vector into another vector. Maybe this could be solved more elegantly, but that shall not be the question here (except if it's absolutely stupid what I'm trying to do, of course.)

void DomainClass::addMembers(vector<DomainMember*>& d){
    for(int i = 0; i < d.size(); i ++){
        this->domains.push_back(d[i]);
    }
}

The vector this->domains is a member with definition:

vector<Domain*> domains;

The compiler tells me: error:

reference to type 'const value_type' (aka 'Domain *const') could not bind to an lvalue of type 'value_type' (aka 'DomainMember *')

I basically understand the problem when I'd like to handle objects BY REFERENCE, BUT in that case, I'd like to insert the elements of d BY VALUE into domains . How can I tell the compiler that he should just make a copy instead of passing references?

What the error tells you is that you try to put an object of type DomainMember* (in d ) in an object of class Domain* (in domains ). The compiler does not know how to cast from DomainMember to Domain .

The problem is not with the copy, it is with the fact that the type of domains should be be vector<DomainMember*> (or d should be a vector<Domain*> , your call) for your push_back to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM