saltfish666 / saltfish666.github.io

my blog
0 stars 0 forks source link

C++语法 #10

Open saltfish666 opened 6 years ago

saltfish666 commented 6 years ago

函数

saltfish666 commented 6 years ago

对象生命周期的钩子函数

saltfish666 commented 6 years ago

观察对象生命周期

#include <iostream>
using namespace std;
class Complex{
    int id;
public:
    Complex(int i){
        id = i;
        cout<<"id="<<id<<"courtor \n";
    }
    ~Complex(){
        cout<<"id="<<id<<"die \n";
    }
};

Complex c1(1);

void func(){
    cout<<"func beagin \n";

    static Complex d2(2);
    Complex d3(3);

    cout<<"func end \n";
}

int main(){

    Complex c1(4);

    {
        Complex c2(5);
    }

    func();

    Complex c3 = 6;

    return 0;
}
/*
id=1courtor 
id=4courtor 
id=5courtor 
id=5die 
func beagin 
id=2courtor 
id=3courtor 
func end 
id=3die 
id=6courtor 
id=6die 
id=4die 
id=2die 
id=1die
 */
saltfish666 commented 6 years ago

友元函数

include

using namespace std;

class Hi{ public: void func(Complex c); };

class Complex{ int id; public: void Complex(int i){ id = i; } friend void Hi::func(Complex c); };

void Hi::func(Complex c) { cout<<c.id; }

int main(){

Complex c = 3;
Hi h;

h.func(c);

return 0;

}

编译一直错,难受
### this 的来源
https://www.bilibili.com/video/av10046030/?p=23

class A{ int i; public: void Hi(){ cout<<"hello"; } };

int main(){

A* p = NULL;
p->Hi();
return 0;

}

saltfish666 commented 6 years ago

常量成员函数

体现纯函数的特性,不会修改所在对象,语法层面的支持。

saltfish666 commented 6 years ago

继承

子类到底从父类继承了什么?

class B: A

saltfish666 commented 6 years ago

复合关系中避免循环定义

class Master;

class Dog{ 
  //Dog d; wrong
  Master *m;
};

class Master{
  Dog d;
};

int main(){
    cout<< sizeof(Master);
}

知道关系(逻辑上更合理,更复合现实,提高代码复用的可能性)

class Master;

class Dog{ 
  //Dog d; wrong
  Master *m;
};

class Master{
  Dog *d;
};

int main(){
    cout<< sizeof(Master);
}
saltfish666 commented 6 years ago

子类的覆盖

class B;

class A{
public:
  int age = 10;
    void hello(){
        cout<<age<<"\n";
    }
};

class B:public A{

    int age = 3;

public:
  void hi(){
      cout<<A::age<<"\n";
      cout<<age<<"\n";
  }
};

int main(){
    cout<< sizeof(A)<<"\n";//4 
    B b;//10
    b.hi();//3
    b.hello();//10
}
/*是不是这样理解,子类的成员变量和父类同名,就会覆盖之;(sizeof 证明)
C++ 中 类就是结构体和与结构体绑定函数,子类继承自父类的函数依然绑定了父类的结构体?*/