1.面向对象:封装、继承、多态
2.类(像一个图纸,不分配空间),类实例化后产生对象(实体)。类是对象的属性与方法的集合。
3.类实例化产生对象,类中的成员变量(可以为变量、指针、数组)是对象的属性(对象的属性值决定对象的状态),类中的成员函数是对象的方法(确定对象的行为)。
4.对象的关系有:包含、继承、关联。
二、类的设计、对象的创建与使用1.类型设计
格式:class 类型名称 {}; 或 struct 类型名称{};
类是把属性和函数(对象的操作)封装为了一个整体。
举例如下:
#includeusing namespace std; const int LEN{ 20 }; class CGoods { //设计一个商品类 public: //访问限定符 char Name[LEN]; int Amount; float Price; float Total_Price; }; int main() { CGoods c1;//定义一个商品类的对象 c1.Amount = 15;//通过对象点运算访问类中成员变量 }
2.对于类中的成员变量/成员函数需要访问限定符:public(公共的)、protected(保护的)、private(私有的)修饰。
对于public共有块:类的对象可以通过对象点运算访问类中成员变量/成员方法。
而protected和private均无法访问(体现封装性)。
3.设计类型用class和struct的区别:
class 类型名称 {}; 类中若未定义访问限定符,其成员变量、成员函数默认为private私有的。
struct 类型名称{}; 类中若未定义访问限定符,其成员变量、成员函数默认为public公有的。
4.通常类中只有成员函数的声明,成员函数的定义(其中可以使用成员变量)在类的设计外。
格式:返回值类型 类名 :: 函数名(参数列表){}
运算符“::”为作用域解析运算符,指出该函数属于哪个类。
#includeusing namespace std; const int LEN{ 20 }; class CGoods { //设计一个商品类 private: //访问限定符 char Name[LEN]; int Amount; float Price; float Total_Price; public: void RegisterGoods(const char*, int, float); void CountTotal(); const char* Get_name(); int Get_amount(); float Get_price(); float Get_totalprice() { return Total_Price;//函数定义也可以写在类设计中 } }; //返回值类型 类名::函数名(参数列表){} void CGoods::RegisterGoods(const char* name, int amount, float price) { strcpy_s(Name, LEN, name); Amount = amount; Price = price; } void CGoods::CountTotal() { Total_Price = Price * Amount; } const char* CGoods::Get_name() { return Name; } int CGoods::Get_amount() { return Amount; } float CGoods::Get_price() { return Price; }
附加:在类中声明+定义和在类中声明、类外定义的区别如下
在类中声明+定义:隐式默认该成员函数为inline内敛函数(可直接将代码嵌套于调用处)
在类中声明、类外定义:需要显式加inline才为内敛函数
5.对象是类的实例。
对象的创建:类名 对象名;
对象的使用:对象.属性(成员变量) 对象.成员方法



