运算符中的后缀++和前缀++重载C++,含义
Postfix ++ and prefix ++ in operatoroverloading C++, meanings
我有这段代码,但我不理解输出。。。
class Complex
{
private:
float re;
float im;
public:
Complex(float r = 0.0, float i = 0.0) : re(r), im(i){};
void Print(){cout << "Re=" << re <<",Im=" << im << endl;}
Complex operator++(); //prefiksna
Complex operator++(int); //postfiksna
};
Complex Complex ::operator++()
{
//First, re and im are incremented
//then a local object is created.
return Complex( ++re, ++im);
}
Complex Complex ::operator++(int k)
{
//First a local object is created
//Then re and im are incremented. WHY is this ??????
return Complex( re++, im++);
}
int main()
{
Complex c1(1.0,2.0), c2;
cout << "c1="; c1.Print();
c2 = c1++;
cout << "c2="; c2.Print();
cout << "c1="; c1.Print();
c2 = ++c1;
cout << "c2="; c2.Print();
cout << "c1="; c1.Print();
return 0;
}
输出为:
1.c1=Re=1,Im=2
2.c2=Re=1,Im=2
3。c1=Re=2,Im=3
4.c2=Re=3,Im=4
5.c1=Re=3,Im=4
有人能解释一下这些输出吗?(1.微不足道,我想我能理解。和5,只是想确保…)我对2的区别很感兴趣。和4。主要是,这还不清楚为什么会是这样。注释中的代码中也有一个问题(为什么是这样????)
你的问题应该像其他人一样结束,他们曾经问过"增量前和增量后意味着什么",但你的老师在尝试教授之前应该学习一些东西:
Complex& Complex ::operator++()
{
//First, re and im are incremented
++re; ++im;
//then there is no need to create a local object.
return *this;
}
通过测试它的方式,优化器可以消除讲师的错误代码所隐含的额外工作。但是,如果你应该学习如何编写前增量运算符和后增量运算符(这是学习它们的含义之外的一步),那么正确地学习如何以及为什么前增量运算符应该比后增量运算符更高效。
相关文章:
- 继承函数的重载解析
- 你能重载对象变量名本身返回的内容吗
- 从父命名空间重载类型
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 重载操作程序时出错>>用于类中的字符串 memebr
- 一个关于在C++中重载布尔运算符的问题
- 不同翻译单元中不可重载的非内联函数定义
- 为什么使用SFINAE而不是函数重载
- 为什么我不能在 C++ 中的特定函数重载中调用同一函数的任何其他重载?
- 将重载的成员函数传递给函数模板
- c++:可变模板和函数重载
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 重载==不适用于二进制树
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 重载运算符new[]的行为取决于析构函数
- 正在尝试重载二进制搜索树分配运算符
- 重载Singly Linked List中的赋值运算符
- 取消引用运算符不能重载