基础
#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;
}
构造函数,析构函数
- 析构函数:对象被删除或者生命周期结束的时候,该函数会触发,可以被重载
- 构造函数:对象创建的时候,会触发函数,不可以重载
#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;
}
虚函数和纯虚函数
- 虚函数:有实际定义的,允许派生类对其进行覆盖式的替换,virtual来修饰,用在类的继承上的
- 纯虚函数:没有实际定义的虚函数就是纯虚函数
- 虚函数的优点:可以预留接口进行分工合作
#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;
}