孙鑫VC++ lession2 掌握C++

    技术2025-08-14  7

    this-> 指针因为方法是在代码段中,对于所有的对象都只有一份拷贝所以在对象在方法调用中,隐含的都会传递一个this指针过去,来区别是那个对象调用的方法

    析构函数只有一种无参的~A() 在这里面调用对象的delete()方法来释放内存

     

    C++写类的时候class A{}; 后面的大括号要加;

    C++中 修饰符这样写,(好像没有类的修饰符)class A{public:  int x;protected:  int y;private:  int z;};

     

     

    #include <iostream.h>class Animal{//C++中只有三种修饰符public protected private //class 跟struct的区别: class默认是private,struct默认是public public: Animal() {  cout<<"Animal construct"<<endl; } Animal(int a){

     } void breathe(){  cout<<"Animal breathe"<<endl; } //C++的虚函数: //不是virtual函数的时候 C++编译器 在编译的时候就绑定了要调用的函数 //是virtual函数的时候 C++编译器 不会绑定要调用的函数,等到运行的时候再决定调用的函数,这种叫做延时绑定 //如果子类有调用子类的函数,如果没有调用父类 virtual void sleep() {  cout<<"Animal sleep"<<endl; }

    //析构函数在没有子类继承的情况下是任意//在有子类继承的情况下 只可以是 public 或者 private 因为子类要调用父类的privateprotected: ~Animal(){  delete this; }};

    class Creature { //C++中的纯虚函数,相当于java中的 abstract函数 //这样的类不能被实例化,继承他的类必须要实现这个方法public: virtual void eat()=0;};class Fish:public Animal,public Creature{public: const int a; Fish():Animal(300),a(400) //默认调用父类的带参数构造 然后给个初始值 {  cout<<"Fish construct"<<endl; }

     void breathe() {  cout<<"Fish breathe"<<endl; }

     void sleep() {  cout<<"Fish sleep"<<endl; } virtual void eat() {

     }

     ~Fish() {

     }};

    void test_Inherit(Animal *animal){  animal->breathe();

     animal->sleep();}

    void main(){ Fish fish; Animal *animal; //能不能强制转换,取决于两个类的内存模型是否一样, //Fish中的内存模型可以分成两个部分:一个是从Animal中继承过来的部分, //所以强制类型转换后,用调用的都是父类animal的方法 //如果是java的话,会调用子类的方法 animal = &fish; test_Inherit(animal);}

    最新回复(0)