|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #include<iostream>
- using namespace std;
- class MyInteger{
- friend ostream& operator<<(ostream& cout, MyInteger myint);
- private:
- int m_num;
- public:
- //构造函数
- MyInteger()
- {
- m_num = 0;
- }
-
- //前置++操作
- MyInteger& operator++()
- {
- m_num++;
- return *this;
- }
-
- //后置++操作
- MyInteger operator++(int)
- {
- MyInteger temp = *this;
- m_num++;
- return temp;
- }
- };
- ostream& operator<<(ostream& cout, MyInteger myint)
- {
- cout << "myint.m_num = " << myint.m_num << endl;
- return cout;
- }
- int main() {
-
- MyInteger myint;
- cout << ++myint << endl;
- cout << myint << endl;
- cout << myint++ << endl;
- cout << myint << endl;
-
- system("pause");
-
- return 0;
-
- }
复制代码
代码如上所示
求问在cout输出那块编译器是怎么知道++在对象前就调用第一个++重载函数,++在对象后就调用第二个++重载函数的
c++规定的就是
operator++ () 是前置 ++重载, operator++(int) 是后置 ++ 重载。
++在对象前就调用 ++(),++在对象后就调用 ++(int)
这很明白啊。
|
|