我目前正在研究一个项目,我的教授希望我们练习使用重载运算符,但最后一个给我带来麻烦的是++增量运算。我遵循了他的示例以及在网上看到的示例,该示例在构建时不会抛出任何错误消息,但似乎无法正常工作。它使运行崩溃,并采用已从0初始化为某个随机数的等级。如果我不尝试增加额定值,那么它不会造成任何麻烦,并且过载的<<操作符可以正常工作,我现在很茫然。
这是我到目前为止的主要工作
list<int> time1{1000, 1200, 1400, 1600};
list<int> time2{ 1100, 1300, 1500, 1700 };
Cinema cinema;
Movie * movie1 = new Movie("Superman", 1988, 11, 8);
*movie1++;
cout << * movie1;
cinema.addMovie(movie1, time1);
这是电影课
class Movie
{
public:
Movie(const string & name, int yyyy, int mm, int dd) : name(name), releaseDate(Date(yyyy, mm, dd)) {};
const Date getReleaseDate();
// other?
bool operator < (Movie& r);
bool operator == (Movie &);
Movie & operator ++ ();
friend ostream & operator << (ostream &, Movie &);
friend ostream & operator << (ostream &, const Movie &);
private:
Movie() = default;
const Date releaseDate;
string name;
int rating = 0;
};
电影课(如果您认为相关的话)
class Cinema
{
public:
Cinema() = default;
Cinema(Cinema &);
void addMovie(Movie *, list<int> & );
friend ostream & operator << (ostream &, Cinema &);
//Movie * operator[](int);
void movieRunningAt(Movie &, list<int> & );
void printShowTimes(const Movie *);
void printAll() const;
private:
std::list<Movie *> movies;
map<const Movie *, list<int>> movie_times;
};
重载的<<运算符可以打印出信息,并且如果我不尝试使用重载的++运算符来提高评分,效果也很好
ostream & operator << (ostream & os, Movie & mo)
{
os << mo.name << " released: " << mo.releaseDate << " rated " << mo.rating << "\n";
return os;
}
//// The const version
ostream & operator << (ostream & os, const Movie & mo)
{
os << mo.name << " released: " << mo.releaseDate << " rated " << mo.rating << "\n";
return os;
}
这是++运算符,用于提高电影的收视率
Movie & Movie::operator ++ ()
{
rating++;
return *this;
}
同样,它不会引发任何错误,只是会导致弹出一堆随机的东西,我认为由于某种内存泄漏,但是我不确定
最佳答案
Operator precedence in C++。后缀运算符++
(后递增)的优先级高于取消引用运算符*
的优先级,因此它首先被应用。*movie1++;
将取消引用movie1
并丢弃结果,然后指针本身递增。
首选的解决方案是根本不使用指针(但这需要对Cinema
类进行更改)
Movie movie1 {"Superman", 1988, 11, 8};
movie1++;
cout << movie1;
或者,您可以使用括号更改优先级:
Movie * movie1 = new Movie("Superman", 1988, 11, 8);
(*movie1)++;
您将发现的下一个问题是您定义了预增量运算符,而不是后增量。现在唯一有效的用法是
++(*movie1);
。后增量运算符通常如下所示:Movie Movie::operator ++ (int)
{
Movie tmp = *this; //you need to make a copy to return it to the caller
++(*this); //use already defined pre-increment operator
return tmp;
}
关于c++ - 如何正确返回带有成员变量的重载运算符++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61749036/