开发者

C++ Vector of class objects

I have a class called Movie with the following private data members:

private:
    string       title_ ;  
    string       director_ ;  
    Movie_Rating rating_ ;  
    unsigned int year_ ;  
    string       url_ ;  
    vector<string> actor_;

It also contains the following copy constructor:

Movie::Movie(Movie& myMovie)  
{  
    title_ = myMovie.title_;  
    director_ = myMovie.director_;  
    rating_ = myMovie.rating_;  
    year_ = myMovie.year_;  
    url_ = myMovie.url_;  
    actor_ = myMovie.actor_;  
}

When I try to create a vector of this c开发者_如何学Class,

vector<Movie> myMovies;

and then accept all the info from a user into a temp Movie object (myMovie1), and then use push back:

myMovies.push_back(myMovie1);

I get the following error:

1>c:\program files (x86)\microsoft visual studio 9.0\vc\include\vector(1233) : error C2558: class 'Movie' : no copy constructor available or copy constructor is declared 'explicit'

Where am I going wrong? It seems it wants a copy constructor but I do have one defined.


My guess is that it's protesting against binding a temporary to a non-const reference. Try Movie::Movie(const Movie & myMovie) as the signature to your copy constructor.


Code should read:

Movie::Movie(const Movie& myMovie)
{
title_ = myMovie.title_;
director_ = myMovie.director_;
rating_ = myMovie.rating_;
year_ = myMovie.year_;
url_ = myMovie.url_;
actor_ = myMovie.actor_;
}


Change copy constructor to

Movie::Movie(Movie const& myMovie)

or remove it completely - it seems that default(shallow copy) is ok in this case.


You copy constructor needs to be like this:

Movie::Movie(const Movie& myMovie)

The const is needed for the compiler to find it.


The elements that go in a vectormust meet the "copy constructible" requirement; that is, they must have a copy constructor available. Now, is your copy constructor private or protected?

In C++11, a vector can also take objects that are movable, although they still need to be copyable if you want to copy the vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜