前面学过用友元关键字修饰全局函数来对运算符进行重载。 下面介绍用类的函数成员来进行函数重载: - class Complex
- {
- public:
- Complex(int a, int b)
- {
- this->a = a;
- this->b = b;
- }
- void printCom()
- {
- cout<<a<<" + "<<b<<"i "<<endl;
- }
-
-
- Complex& operator++()
- {
- this->a++;
- this->b++;
- return *this;
- }
-
-
-
- Complex operator++(int)
- {
- Complex tmp = *this;
- this->a++;
- this->b++;
- return tmp;
- }
-
- private:
- int a;
- int b;
- };
-
- void Test1()
- {
-
- Complex c1(1, 2);
-
-
- ++c1;
- c1.printCom();
-
-
- c1++;
- c1.printCom();
-
- system("pause");
- }
注:1、前置++与后置++的返回值是不同的,前者需要先完成自加再取值,因此需要完成自加自后将自己返回(采用引用做返回值),后者需要先取值再加加,因此需要先定义一个临时变量缓存当前值,然后在对自身加加,最后返回的是临时变量即未自加之前的值。 2、前置++与后置++的函数参数也是不同的:前置++:Complex& operator++();后置++Complex operator++(int),为了区别前置和后置的,在后置里要加个占位符。
那什么情况下用带友元关键字的全局函数重载操作符?什么情况下用类的成员函数重载操作符呢? 先看个例子: 此声明语句放到上面类里面: - friend ostream& operator<<(ostream &out, Complex &c1);
<<运算符重载用友元关键字修饰的全局函数:- ostream& operator<<(ostream &out, Complex &c1)
- {
- out<<c1.a<<" + "<<c1.b<<"i "<<endl;
- return out;
- }
ostream是什么鬼??
为什么他要用友元函数重载呢?? 那你用类成员函数重载试试,你可以再ostream类里添加这个重载类成员函数吗?肯定不能因此这种情况乖乖用友元函数吧。 看看测试函数吧:
- void Test2()
- {
- Complex c1(1, 2);
- int a = 10;
- char *p = "addddd";
- cout<<"a"<<a<<endl;
- cout<<"p"<<p<<endl;
-
-
- cout<<c1;
-
-
-
-
-
- cout<<c1<<"abcc";
-
-
-
-
-
-
- }
|