C++ 类和对象
- 类是对一组对象共性的抽象
- 包含成员和方法,成员和方法都属于类的成员。成员描述对象的属性,方法描述了对象的行为。
- 类是 C++ 的核心特性,用户自定义类型。
对象可以是人们要研究的任何事物,万事万物均可看作对象,从简单的整数到复杂的飞机、卫星等均可以看作对象
类的定义
class Student{
char name[20]; //名字 类的属性 默认为私有
int age; //年龄
int number; //学号
float height; //身高
float weight; //体重
public: //修饰方法为公有
void SetName(char *name) //类的方法
{
memcpy(this->name, name, strlen(name)); //每个对象都有一个this指针指向自身
}
void SetAge(int age)
{
this->age = age;
}
void SetHeight(float height)
{
this->height = height;
}
void SetWeight(float weight)
{
this->weight = weight;
}
char *GetName(void)
{
return this->name;
}
int GetAge(void)
{
return this->age;
}
float GetHeight(void)
{
return this->height;
}
float GetWeight(void)
{
return this->weight;
}
};
方法直接定义在类中为内联方法
方法可以定义在外部:
语法
[类型] <方法所属类名> <函数名> ( < 形参 > )
class man
{
char name[20];
int age;
...
}
void man :: Eat(void)
{
...
}
外部定义方法要成为内联方法使用关键词inline修饰
类一般包括以下成员:
- 数据成员
- 成员函数
- 构造函数
可以有多个构造函数,构造函数可以重载。- 作用:
创建对象时自动执行对对象进行初始化 - 格式:
- 作用:
<类名> ( <参数表> )
与类同名,没有返回值,可外部定义,可内联,可重载。
- 析构函数
- 作用
撤销对象时进行清理工作,释放其占有的内存空间。
- 格式:
- 作用
~ <类名>( )
与类同名,前缀波浪号“~”以区分构造函数
无形参,不能重载。
无返回值类型。
实例化对象
int main(void)
{
Student guangjieMVP; //实例化一个学生对象
guangjieMVP.SetName("guangjieMVP");
guangjieMVP.SetAge(25);
guangjieMVP.SetHeight(165.0);
guangjieMVP.SetWeight(110.0);
cout << "姓名 :" << guangjieMVP.GetName() << endl;
cout << "年龄 :" << guangjieMVP.GetAge() << endl;
cout << "身高 :" << guangjieMVP.GetHeight() << endl;
cout << "体重 :" << guangjieMVP.GetWeight() << endl;
return 0;
}