1. 程式人生 > 其它 >程式設計與演算法(三)C++面向物件程式設計 第三週 相關筆記

程式設計與演算法(三)C++面向物件程式設計 第三週 相關筆記

1、this指標的運用

指向當前函式作用類的指標

相當於翻譯為C語言,r.run() = run(test * this)

#include<bits/stdc++.h>
using namespace std;
class test{
    private:
        double real,imag;
    public:
        test(double r,double i):real(r),imag(i)
        {}
        void add_one(){
            this->real ++;
        }
        
void get_(){ cout<<this->real<<" "<<this->imag<<endl; } }; int main(){ test a(1,2); a.add_one(); a.get_(); }
View Code
#include<bits/stdc++.h>
using namespace std;
class test{
    private:
        double real,imag;
    public:
        test(
double r,double i):real(r),imag(i) void out(){ cout<<"Hello"<<endl; } }; int main(){ test* p = NULL; p->out(); }
View Code

2、靜態成員

分為靜態成員函式,靜態成員變數

相當於全域性函式,全域性變數

定義靜態成員變數需要先說明

int CRectangle::nTotleArea = 0;

靜態成員函式內不能訪問非靜態變數與非靜態函式

#include<bits/stdc++.h>
using
namespace std; class Rectangle{ private: int w,h; static int total_area; static int total_number; public: Rectangle(int _w,int _h){ w = _w; h = _h; total_area += w*h; total_number++; } Rectangle(Rectangle& r){ w = r.w; h = r.h; total_area += w*h; total_number++; } ~Rectangle(){ total_area -= w*h; total_number--; } static void out(){ cout<<total_number<<" "<<total_area<<endl; } }; int Rectangle::total_number = 0; int Rectangle::total_area = 0; int main(){ Rectangle r1(1,2); Rectangle* r2 = new Rectangle(2,4); Rectangle r3(2,3); Rectangle::out(); delete r2; Rectangle::out(); Rectangle r4 = r1; Rectangle::out(); return 0; } 輸出: 3 16 2 8 3 10
View Code

新增建構函式後預設無參建構函式消失

但是複製建構函式依然在

3、成員物件與封閉類

有成員物件的類叫做封閉類

封閉類的建構函式與解構函式的執行順序相反

建構函式都是先生產成員物件,在操作封閉類

解構函式先操作封閉類先操作成員物件

#include<bits/stdc++.h>
using namespace std;
class tyre{
public:
    tyre(){
        cout<<"tyre constructor"<<endl;
    }
    ~tyre(){
        cout<<"tyre destructor"<<endl;
    }
};
class engine{
public:
    engine(){
        cout<<"engine constructor"<<endl;
    }
    ~engine(){
        cout<<"engine destructor"<<endl;
    }
};
class Car{
    tyre t;
    engine e;
    public:
        Car(){
            cout<<"car constructor"<<endl;
        }
        ~Car(){
            cout<<"car destructor"<<endl;
        }
};


int main(){
    Car c;
    return 0;
}

輸出:
tyre constructor
engine constructor
car constructor
car destructor
engine destructor
tyre destructor
View Code

封閉類的複製建構函式還是呼叫其成員的物件的複製建構函式

pass

4、友元 friend

一個類友元函式可以訪問該類的私有成員

一個類友元類可以訪問該類的私有成員

#include<bits/stdc++.h>
using namespace std;

class Car{
    int a = 1,b = 2;
    public:
        friend void get_(Car c);
};
//改成指標也可
//class 也行
void get_(Car c){
    cout<<c.a<<" "<<c.b<<endl;
}

int main(){
    Car c;
    get_(c);
    return 0;
}
View Code