Qt(X):C++基础

基础

#include <iostream>

using namespace std;
class student
{
public:
    char name[64];
    int  age;
    void test(){//在类里面写方法
        cout<<123<<endl;
    }
    void test2();//声明函数,实现函数可以写在类的里面,也可以写在外面
};

void student::test2(){//不加::就会被识别为普通的函数
    cout<<1211<<endl;
};

int main()
{
    student my1;//直接定义
    student *my = new student;//在堆里面定义
    //delete my ;//删除对象,释放堆里面的内存
    my1.age=18;
    my->age=19;
    cout<<my->age<<endl;
    cout<<my1.age<<endl;

    my1.test();
    my1.test2();
    return 0;
}

构造函数,析构函数

  1. 析构函数:对象被删除或者生命周期结束的时候,该函数会触发,可以被重载
  2. 构造函数:对象创建的时候,会触发函数,不可以重载
#include <iostream>

using namespace std;
class student
{
public:
     student(void);
     ~student(void);

};
student::student(void){
    cout<<"this is a constructor"<<endl;
}

student::~student(void){
    cout<<"this is a inv-constructor"<<endl;
}
int main()
{
    student *s1 = new student;
    delete s1;
    return 0;
}

继承

类的继承允许我们在新的类里面继承父类的public和protected部分,private不可以被继承

#include <iostream>

using namespace std;
class student
{
public:
     student(void);
     ~student(void);
     void father_print(){
         cout<<"form father "<<endl;
     }


};
student::student(void){
    cout<<"this is a constructor"<<endl;
}

student::~student(void){
    cout<<"this is a inv-constructor"<<endl;
}
class student1:public student{
public :
    void son_print(){
        cout<<"form sub class"<<endl;
    }
};
int main()
{
    student1 *s1 = new student1;
    s1->father_print();
    s1->son_print();
    delete s1;
    return 0;
}

虚函数和纯虚函数

  1. 虚函数:有实际定义的,允许派生类对其进行覆盖式的替换,virtual来修饰,用在类的继承上的
  2. 纯虚函数:没有实际定义的虚函数就是纯虚函数
  3. 虚函数的优点:可以预留接口进行分工合作
#include <iostream>

using namespace std;
class student
{
public:
     student(void);
     ~student(void);
     void father_print(){
         cout<<"form father "<<endl;
     }
     virtual void imagefunc(){
         cout<<"this is image function from father class"<<endl;
     }
     virtual void pureimagefunc(){}


};
student::student(void){
    cout<<"this is a constructor"<<endl;
}

student::~student(void){
    cout<<"this is a inv-constructor"<<endl;
}


class student1:public student{
public :
    void son_print(){
        cout<<"form sub class"<<endl;
    }

     void iamgefunc(){
        cout<<"this is image function from son class"<<endl;
    }

     void pureimagefunc(){
         cout<<"this is pure virtual function from son class"<<endl;
     }
};
int main()
{
    student1 *s1 = new student1;
    s1->father_print();
    s1->son_print();
    s1->iamgefunc();
    s1->pureimagefunc();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值