您的复制构造函数全错了。它需要看起来像这样:
class Movie {
public:
std::string *movie_name;
std::string *age_rating;
int *view_count;
int *rating;
Movie(const Movie &source) :
movie_name(new string(*(source.movie_name))),
age_rating(new string(*(source.age_rating))),
view_count(new int(*(source.view_count))),
rating(new int(*(source.rating)))
{
}
...
};
您还需要根据3/5/0 的规则实现析构函数和复制赋值运算符,以及在 C++11 及更高版本中的移动构造函数和移动赋值运算符,例如:
class Movie {
public:
std::string *movie_name;
std::string *age_rating;
int *view_count;
int *rating;
Movie() :
movie_name(new string),
age_rating(new string),
view_count(new int(0)),
rating(new int(0))
{
}
Movie(const Movie &source) :
movie_name(new string(*(source.movie_name))),
age_rating(new string(*(source.age_rating))),
view_count(new int(*(source.view_count))),
rating(new int(*(source.rating)))
{
}
Movie(Movie &&source) :
movie_name(source.movie_name),
age_rating(source.age_rating),
view_count(source.view_count),
rating(source.rating)
{
source.movie_name = nullptr;
source.age_rating = nullptr;
source.view_count = nullptr;
source.rating = nullptr;
}
~Movie()
{
delete movie_name;
delete age_rating;
delete view_count;
delete rating;
}
Movie& operator=(const Movie &source)
{
if (&source != this)
{
*movie_name = *(source.movie_name);
*age_rating = *(source.age_rating);
*view_count = *(source.view_count);
*rating = *(source.rating);
}
return *this;
}
Movie& operator=(Movie &&source)
{
Movie temp(std::move(source));
std::swap(movie_name, temp.movie_name);
std::swap(age_rating, temp.age_rating);
std::swap(view_count, temp.view_count);
std::swap(rating, temp.rating);
return *this;
}
};
您可以通过使用智能指针来减轻手动管理内存分配的一些风险:
#include <memory>
class Movie {
public:
std::unique_ptr<std::string> movie_name(new string);
std::unique_ptr<std::string> age_rating(new string);
std::unique_ptr<int> view_count(new int(0));
std::unique_ptr<int> rating(new int(0));
Movie() = default;
Movie(const Movie &source) :
movie_name(new string(*(source.movie_name))),
age_rating(new string(*(source.age_rating))),
view_count(new int(*(source.view_count))),
rating(new int(*(source.rating)))
{
}
Movie(Movie &&source) = default;
~Movie() = default;
Movie& operator=(const Movie &source)
{
if (&source != this)
{
*movie_name = *(source.movie_name);
*age_rating = *(source.age_rating);
*view_count = *(source.view_count);
*rating = *(source.rating);
}
return *this;
}
Movie& operator=(Movie &&source) = default;
};
但实际上,在这种情况下根本没有充分的理由使用指针。完全摆脱指针,让编译器自动生成适当的构造函数、析构函数和赋值运算符,为您完成管理内存和复制值的所有艰苦工作:
class Movie {
public:
std::string movie_name;
std::string age_rating;
int view_count = 0;
int rating = 0;
// everything is auto-generated for you!
};