在C 中,为什么使用或不作为结果值获得不同的结果
In C++, why do I get different results using or not reference as result value?
class point
{
private:
double x,y;
public:
point(double x=0.0, double y=0.0)
{
this->x=x;
this->y=y;
}
point operator++()
{
this->x=this->x+1.0;
this->y=this->y+1.0;
return *this;
}
point& operator++(int)
{
point p=point(this->x, this->y);
++(*this);
return p;
}
ostream& operator<< (ostream& o)
{
o << "X: " << this->x << endl << "Y: " << this->y;
return o;
}
friend ostream& operator<< (ostream& o,point p)
{
o << "X: " << p.x << endl << "Y: " << p.y;
return o;
}
};
int main()
{
point p = point();
p++ << cout << endl; // first output
cout << p++ << endl;// second output
}
我不明白为什么第一个输出不正确(x:6.95333e-310 y:6.9532e-310),而第二个输出是正确的(x:1 y:1)。
以及为什么通过在后收入操作员的返回值结束时删除&
来解决此问题?
当您返回对本地变量的引用时,使用该引用是未定义的行为。
您的编译器应该警告您。如果不是这样,请提高编译器警告级别,并注意警告。
point& operator++()
point operator++(int)
是正确的返回值。
您的其余代码看起来都很好。
我将删除using namespace std;
,然后将++
的实现更改为:
++x;
++y;
return *this;
相关文章:
- 计算幂级数的数学结果不正确
- Fmod 函数清楚地输出一个预期的双精度值,但 if(fmod == 预期的双精度值)的计算结果不是 true
- 运行函数作为 constexpr 和不作为 constexpr
- 回复计划游戏结果不会显示
- Openmp结果不稳健
- 术语的计算结果不是采用0个参数的函数
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 错误 C2064:术语的计算结果不是采用 3 个参数的函数
- 如何查找导致结果不一致的代码
- 使用动态分配的数组进行矩阵乘法;结果不正确
- C++:术语的计算结果不是采用 1 个参数的函数
- 在线程错误 C2064 中:term 的计算结果不为 0 个参数的函数
- 错误 C2064:term 的计算结果不是采用 1 个参数的函数 - 关于线程的一些东西
- boost::d ynamic_bitset 与 std::vector 的结果不一致<bool>?
- C++ 3 for 循环中,结果不应重复
- 提升线程:术语的计算结果不为 0 个参数
- 检查不作为单个条目的STDIN输入
- 功能模板与Variadic模板过载:Intel C 编译器版本18产生的结果不同于其他编译器.英特尔是错误的
- 在C 中,为什么使用或不作为结果值获得不同的结果
- 函数的结果不能作为引用传递