C++补充笔记(六)

第六章

6.1运算符重载再实践

发现自己对运算符重载掌握得仍旧不熟练,故通过复数(Complex)类的实践来巩固一下。下面给出文件结构与具体代码:
这里写图片描述

Complex.hpp文件:

#ifndef Complex_hpp
#define Complex_hpp

#include <iostream>
using namespace std;

class Complex{

    friend Complex operator++(Complex &);       //通过友元函数重载前置++
    friend Complex operator++(Complex &,int);   //通过友元函数重载后置++
    friend ostream & operator << (ostream &,const Complex &);   //通过友元函数重载输出符<<

private:
    double real;
    double imag;

public:
    Complex(double = 0,double = 0);

    Complex  operator += (Complex &);   //通过成员函数重载+=
    Complex  operator--();              //通过成员函数重载前置--
    Complex  operator--(int);           //通过成员函数重载后置--
};

#endif /* Complex_hpp */

Complex.cpp文件:

#include "Complex.hpp"
#include <iostream>
#include <iomanip>
using namespace std;

Complex::Complex(double r,double i)
:real(r),imag(i)
{
    //Nothing
}

Complex Complex::operator+=(Complex & c){
    real += c.real;
    imag += c.imag;
    return *this;
}

Complex Complex::operator--(){
    --real;
    --imag;
    return *this;
}

Complex Complex::operator--(int){
    Complex temp = *this;
    --real;
    --imag;
    return temp;
}

Complex operator++(Complex & c){
    ++c.real;
    ++c.imag;
    return c;
}

Complex operator++(Complex & c,int){
    Complex temp = c;
    ++c.real;
    ++c.imag;
    return temp;
}

ostream & operator << (ostream & output,const Complex & c){
    output << noshowpos << c.real << showpos << c.imag << "i";
    return output;
}

main.cpp文件:

#include "Complex.hpp"
using namespace std;

int main(){
    Complex c1(1.2,-2);
    Complex c2(-3,4.2);

    cout << "c1 = " << c1 << endl;
    cout << "++c1 = " << ++c1 << endl;
    cout << "c1 = " << c1 << endl;
    cout << "c1++ = " << c1++ << endl;
    cout << "c1 = " << c1 << endl << endl;

    cout << "c2 = " << c2 << endl;
    cout << "--c2 = " << --c2 << endl;
    cout << "c2 = " << c2 << endl;
    cout << "c2-- = " << c2-- << endl;
    cout << "c2 = " << c2 << endl << endl;

    c1 += c2;
    cout << "c1+=c2 is: " << c1 << endl;
}

测试结果如下所示:
这里写图片描述

经过测试,我发现对于前置++或- -运算符,通过友元函数或成员函数重载时返回值既可以是Complex,也可以是Complex& 。也就是说:

 friend Complex operator++(Complex &);  
 friend Complex & operator++(Complex &); 
 //以及
 Complex  operator--(); 
 Complex  & operator--();  

都是可行的。

6.2虚函数

  • 静态成员函数不能声明为虚函数
  • 内联成员函数不能声明为虚函数
  • 构造函数不能声明为虚函数
  • 析构函数可以声明为虚函数

猜你喜欢

转载自blog.csdn.net/qq_32925781/article/details/79448785