
C++ 运算符重载,解释一下
例8.3定义一个CInt类,类中只有一个数据成员i,两个运算符“++”的重载函数,一个没有参数,实现的是前置运算符重载,另一个有一个整型参数,实现后置运算符重载。#inc...
例8.3 定义一个CInt类,类中只有一个数据成员i,两个运算符“++”的重载函数,一个没有参数,实现的是前置运算符重载,另一个有一个整型参数,实现后置运算符重载。
#include "iostream.h"
class CInt
{
private:
int i;
public:
CInt(int a=0);
void Print();
CInt operator ++();
CInt operator ++(int);
};
CInt::CInt (int a)
{
i = a;
}
void CInt::Print()
{
cout << "i=" << i << endl;
}
CInt CInt::operator ++()
{
CInt temp;
temp.i = ++i;
return temp;
}
CInt CInt::operator ++(int)
{
CInt temp;
temp.i = i++;
return temp;
}
void main(void)
{
CInt a(5), b(5), c, d;
c = a++;
d = ++b;
cout << "a: ";
a.Print();
cout << "b: ";
b.Print();
cout << "c: ";
c.Print();
cout << "d: ";
d.Print();
}
程序运行结果为:
a: i=6
b: i=6
c: i=5
d: i=6
请问c和d的值是怎么得来的? 展开
#include "iostream.h"
class CInt
{
private:
int i;
public:
CInt(int a=0);
void Print();
CInt operator ++();
CInt operator ++(int);
};
CInt::CInt (int a)
{
i = a;
}
void CInt::Print()
{
cout << "i=" << i << endl;
}
CInt CInt::operator ++()
{
CInt temp;
temp.i = ++i;
return temp;
}
CInt CInt::operator ++(int)
{
CInt temp;
temp.i = i++;
return temp;
}
void main(void)
{
CInt a(5), b(5), c, d;
c = a++;
d = ++b;
cout << "a: ";
a.Print();
cout << "b: ";
b.Print();
cout << "c: ";
c.Print();
cout << "d: ";
d.Print();
}
程序运行结果为:
a: i=6
b: i=6
c: i=5
d: i=6
请问c和d的值是怎么得来的? 展开
2个回答
展开全部
c = a++;
d = ++b;
//=====
严格来说你不能用c= 和d= 的。除非你重载了=运算符。虽然能在某些编译器下通过。
另外既然是自加预算,就应该这样
CInt& operator ++();
CInt& operator ++(int);
你问的问题书上都已经讲的很清楚明了了,诸如c++语言程序设计之类的书。
d = ++b;
//=====
严格来说你不能用c= 和d= 的。除非你重载了=运算符。虽然能在某些编译器下通过。
另外既然是自加预算,就应该这样
CInt& operator ++();
CInt& operator ++(int);
你问的问题书上都已经讲的很清楚明了了,诸如c++语言程序设计之类的书。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询