天天看點

C++從入門到精通——重載函數

  • 重載
  • 一個與之前已經在該作用域聲明過的函數或者方法具有相同名稱的聲明,但是他們的參數清單和定義實作不相同。重載聲明,會根據傳入類型的不用來選取最合适的定義。選取最優函數或者運算符的過程也叫重載決策。
#include <iostream>

using namespace std;

class PrintData {
public:
    void print(int i) {
        cout << "int i is :" << i << endl;
    }

    void print(float i) {
        cout << "float i is :" << i << endl;
    }

    void print(double i) {
        cout << "double i is :" << i << endl;
    }

    void print(int *i) {
        cout << "ptr i is :" << *i << endl;
    }
};

int main() {
    PrintData print_line = PrintData();
    print_line.print(1);
    print_line.print(float (1.));
    print_line.print(1.1245666666666666666666);
    int i = 1;
    print_line.print(&i);
    return 0;
}      
  • 運算符重載
  • 對象之間的相加,傳回最終相同的對象,大多數的重載運算符可被定義為普通的非成員函數或者被定義為類成員函數。我們也可以為每次操作傳遞兩個參數。定義自由化,完全靠自己。
#include <iostream>

using namespace std;

class Box{
private:
    double length;
    double breadth;
    double height;
public:
    double getVolume()
    {
        return length*breadth*height;
    }
    void setLength(double length){
        this->length = length;
    }
    void setBreadth(double breadth){
        this->breadth = breadth;
    }
    void setHeight(double height){
        this->height = height;
    }
    Box operator+(const Box&b){
        Box box;
        box.length = this->length+b.length;
        box.breadth = this->breadth+b.breadth;
        box.height = this->height+b.height;
        return box;
    }
};

int main() {
    Box Box1;
    Box Box2;
    Box Box3;

    double volume;

    Box1.setLength(6.0);
    Box1.setBreadth(7.0);
    Box1.setHeight(8.0);



    Box2.setLength(12.0);
    Box2.setBreadth(13.0);
    Box2.setHeight(10.0);

    volume= Box1.getVolume();
    cout<<"Volume of Box1:"<<volume<<endl;
    // box2 的體積
    volume = Box2.getVolume();
    cout<<"Volume of Box2:"<<volume<<endl;

    Box3 = Box1+Box2;
    volume = Box3.getVolume();
    cout<<"Volume of Box3:"<<volume<<endl;
    return 0;


}