日期 | 变更记录 |
---|---|
2021-10-21 | 创建 |
类的定义
类的实例称为对象
类中的变量和函数称为成员
类成员可以在类的共有或私有部分声明
在公有部分中声明的成员可以被该类外部的函数访问
私有部分不可被该类外部的函数访问
构造函数
函数名与类名相同的特殊的函数,这个函数是没有返回值的
与所属的类同名
构造函数没有返回值
析构函数
析构函数:函数名与类型相同,前面有个~
对象释放的时候回自动调用析构函数
析构函数没有返回值,也不带参数
this指针
编译器在执行的时候不知道是谁的属性,所以出现了this指针
用法this->name = 25
静态成员
同一个类的所有对象共享static数据项
只在类的内部可见
生命周期会贯穿整个周期
将一个静态成员声明为类的私有成员,则只有类的成员函数可以访问它;将其声明为类的公有成员,则可以通过类名访问它(ex:class(类名)::static(静态成员的公有成员)
new
用于类的对象创建内存空间
类似于c的malloc
delete
销毁由new创建的对象
使用完内存后,使用delete将其释放
使用new分配对象数组,必须在delete语句中使用[](ex: delete []ptr)
对象数组
对象数组声明
class_name object_array[length];
对象数组使用
object_array[index].func()
对象数组初始化
class_name object_array[length]=xxxx
Example
类的定义
#if 1
#include <iostream>
using namespace std;
//public:可以在类内或者类外访问
//private:可以在类内,不能在类外访问
//protected:可以在类内,不能在类外访问
class stu
{
private:
int ID;
char sex;
const int heigh = 20;
protected:
int age;
public:
void fun()
{
cout << "ID:" << ID << endl;
}
int get_ID()
{
return this->ID;
}
void set_ID(int ID)
{
this->ID = ID;
}
};
int main()
{
stu s1;
s1.set_ID(100);
cout << "s1.get_ID():" << s1.get_ID() << endl;;
return 0;
}
#endif
构造函数
#if 1
#include <iostream>
using namespace std;
//构造函数
//函数名与类名相同的特殊的函数,这个函数是没有返回值的
//构造函数实例化对象的时候自动调用
class stu
{
private:
int ID;
char sex;
const int heigh;
public:
stu():heigh(20),sex('M')
{
cout << "我是不带参数的构造函数" << endl;
ID = 20;
}
stu(int ID, char sex):heigh(20)
{
cout << "我是带参数的构造函数" << endl;
this->ID = ID;
this->sex = sex;
}
void display();// 构造函数
};
void stu::display()//在类中声明构造函数,在外部定义
{
cout << "ID:" << ID << endl;
cout << "SEX:" << sex << endl;
cout << "heigh:" << heigh << endl;
}
int main()
{
//stu s1(100, 'S');
stu s1;
s1.display();
return 0;
}
#endif
析构函数
#if 1
#include <iostream>
#include <string.h>
using namespace std;
class stu
{
private:
char *name;
int age;
static int cnt;
public:
stu();
stu(const char name[], int age);
~stu();
void setName(char name[]);
char *getName();
void setAge(int age);
int getAge();
void cntnow()
{
cout << "cnt:" << cnt << endl;
}
//静态成员方法只能访问静态成员函数
static void fun()
{
cnt++;
}
};
int stu::cnt = 0;
stu::stu()
{
cout << "无参数的构造函数" << endl;
this->name = new char[20];
strcpy(name, "小明");
age = 20;
cnt++;
}
stu::stu(const char name[], int age)
{
cout << "有参数的构造函数" << endl;
this->name = new char[20];
strcpy(this->name, name);
this->age = age;
cnt++;
}
//析构函数:函数名与类型相同,前面有个~
//对象释放的时候回自动调用析构函数
//里面用于释放一些手动分配的空间
stu::~stu()
{
cout << "我是析构函数" << endl;
delete[] this->name;
}
void stu::setName(char name[])
{
strcpy(this->name, name);
}
char* stu::getName()
{
return this->name;
}
void stu::setAge(int age)
{
this->age = age;
}
int stu::getAge()
{
return age;
}
void test()
{
stu s1;
cout << "s1:name" << s1.getName() << endl;
cout << "s1:age" << s1.getAge() << endl;
s1.cntnow();//1
}
int main()
{
test();
stu s2("xiaohong", 30);
cout << "s2:name" << s2.getName() << endl;
cout << "s2:age" << s2.getAge() << endl;
stu s3;
stu s4;
s2.cntnow();//4
s3.cntnow();//
s4.cntnow();//4
stu* sp = new stu;
sp->cntnow();
return 0;
}
#endif