邮寄增量不发布 [英] post increment not post
问题描述
我想知道为什么以下程序输出1而不是0.
#include< iostream>
class a {
int v;
public:
a():v(0){}
A和operator ++(int){
v ++;
}
operator int&(){
return v; < br $>
}
};
int main(){
a aa;
//我打算用0初始化b,然后递增一个
int b = aa ++;
std :: cout<< b<< std :: endl;
//没发生
}
谢谢,
罗伯特
I''d like to know why the following program outputs 1, and not 0.
#include <iostream>
class a {
int v;
public:
a():v(0){}
a& operator++(int) {
v++;
}
operator int&() {
return v;
}
};
int main() {
a aa;
// I intend b to initialize b with 0, then increment a
int b = aa++;
std::cout << b << std::endl;
// didn''t happen
}
Thanks,
Robert
推荐答案
Robert Swan写道:
Robert Swan wrote:
我想知道为什么以下程序输出1,以及不是0.
我很惊讶它输出任何东西。它不应该编译。
#include< iostream>
一级{
int v;
公开:> a():v(0){}
a& operator ++(int){
v ++;
此函数被定义为没有''return''语句,尽管非空函数需要一个
,这不是c-tor或者d-tor。
我不知道你在做什么。该程序格式不正确。
}
operator int&(){
返回v;
}
};
int main(){
aa;
//我打算用0初始化b,然后递增一个
int b = aa ++;
std :: cout< ;< b<< std :: endl;
//没发生
}
I''d like to know why the following program outputs 1, and not 0.
I am surprised it outputs anything. It''s not supposed to compile.
#include <iostream>
class a {
int v;
public:
a():v(0){}
a& operator++(int) {
v++;
This function is defined to have no ''return'' statement although one
is required for non-void function which is not a c-tor or d-tor.
It is unknown what you _intended_ to do. The program is ill-formed.
}
operator int&() {
return v;
}
};
int main() {
a aa;
// I intend b to initialize b with 0, then increment a
int b = aa++;
std::cout << b << std::endl;
// didn''t happen
}
你需要对operator ++做点什么,然后我们可以谈谈。
V
You need to do something about the operator++, then we can talk.
V
Robert Swan写道:
Robert Swan wrote:
我想知道为什么以下程序输出1,而不是0.
#include< iostream>
a类{
int v;
public:
a():v(0){}
a& operator ++(int){
v ++;
I''d like to know why the following program outputs 1, and not 0.
#include <iostream>
class a {
int v;
public:
a():v(0){}
a& operator++(int) {
v++;
你错过了这里的回报。
如果你返回
*这
然后,程序应该像你观察到的那样。
v成员增加并应用副作用
在运算符++返回之前。
如果你想让它表现得像一个真正的后增量,你需要返回一个旧对象的副本。
a operator ++(int){
a temp(* this);
v ++;
返回a;
}
You''re missing a return here.
If you return
*this
then, the program should behave like you observed.
The v member is incremented and the side effect applied
before the operator++ returns.
If you want it to behave like a real postincrement, you
need to return a copy of the old object.
a operator++(int) {
a temp(*this);
v++;
return a;
}
Robert Swan写道:
Robert Swan wrote:
operator int&(){
返回v;
}
operator int&() {
return v;
}
顺便说一句,在这里返回引用可能是一个坏主意。
By the way, returning a reference here is probably a bad idea.
这篇关于邮寄增量不发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!