1. 封装
(1)语法
class 类名{ 访问权限 : 属性 / 行为 };
class Circle
{
public: // 访问权限
int r;
double s;
double sq(){
return 2*r*s;
}
};
int main()
{
Circle c1;
c1.r = 2;
c1.s = 2.1;
c1.sq();
}
(2)构造函数和析构函数
01 构造函数语法:类名() {};可以重载;没有返回值也不写void;
02 析构函数语法:~类名(){};不可以重载;没有返回值也不写void;
03 对象的初始化和清理:构造函数进行初始化操作,析构函数进行清理操作。
class Person
{
Person()
{
cout << "构造函数的调用" << endl;
}
~Person()
{
cout << "析构函数的调用" << endl;
}
};
(3)构造函数的分类和调用
01 分类:
001 按参数分为:有参构造和无参构造(默认)
002 按类型分为:普通构造和拷贝构造
class Person
{
Person (int a)
{
age = a;
cout << "有参构造函数的调用" << endl;
}
// 拷贝构造函数
Person(const Person &p)
{
age = p.age;
}
int age;
};
02 三种调用方式:
001 括号法
002 显示法
003 隐式转换法
class Person
{
Person()
{
cout << "无参构造函数的调用" << endl;
}
Person (int a)
{
age = a;
cout << "有参构造函数的调用" << endl;
}
// 拷贝构造函数
Person(const Person &p)
{
age = p.age;
cout << "拷贝构造函数的调用" << endl;
}
int age;
};
//括号法
void test01()
{
Person p1; //默认构造函数调用
Person p2(10); //有参构造函数调用
Person p3(p2); //拷贝构造函数调用
};
//显示法
void test01()
{
Person p1; //默认构造函数调用
Person p2 = Person p2(10); //有参构造函数调用
Person p3 = Person p3(p2); //拷贝构造函数调用
};
(4)初始化列表
01 语法:构造函数() : 属性1(值1), 属性2(值2)……{}
class Person
{
// 传统初始化方式
Person (int a, int b, int c)
{
M_a =a;
M_b =b;
M_c =c;
}
// 初始化列表初始化属性
Person(int a, int b, int c) : M_a(a), M_b(b), M_c(c) {}
int M_a;
int M_b;
int M_c;
};
void test()
{
Person p(10, 20, 30);
cout << M_a << M_b << M_c << endl;
};
2. 继承
(1)语法
class 子类名称 : 继承方式 父类名称{……};
class Person
{
public:
int age;
string name;
};
class Student : public Person
{
public:
cout<< "独有的" << endl;
};
(2)多继承语法
class 子类 : 继承方式 父类1, 继承方式 父类2, ……
class Person
{
public:
int age;
string name;
};
class People
{
public:
int age;
string name;
};
class Student : public Person, public People
{
public:
cout<< "独有的" << endl;
};