1. 类的定义
- class为定义类的关键字,className为类的名字,{}中为类的主体。
class className
{
};
- 类的定义方式:①声明和定义全部放在类体中,②声明放在.h文件中,类的定义放在.cpp文件中。
class Student
{
public:
void SetStudentInfo(const char* name, const char* gender, int age)
{
strcpy(_name, name);
strcpy(_gender, gender);
_age = age;
}
void PrintStudentInfo()
{
cout << _name << " " << _gender << " " << _age << endl;
}
char _name[20];
char _gender[3];
int _age;
};
void test()
{
Student stu;
stu.SetStudentInfo("acd", "男", 30);
stu.PrintStudentInfo();
cout << stu._gender << endl;
}
2. 类的访问限定符
- public(公有):修饰的成员在类外可以被直接访问;
- protected(保护)private(私有):修饰的成员在类外不能直接被访问;
- 访问权限作用域:从该访问限定符出现的位置开始直到下一个访问限定符出现为止;
- class默认访问权限为private。
3. 类的大小
- 一个类的大小实际上就是在进行内存对齐后,该类中“成员变量”之和;
- 空类的大小:编译器给了空类一个字节来唯一标识这个类。
class A
{
public:
int _a;
};
class B
{
public:
int fun1(int a, int b)
{
return a + b;
}
public:
int _a;
};
class C
{
public:
int fun1(int a, int b)
{
return a + b;
}
};
class D
{
};
4. this指针
- this指针:C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有成员变量的操作,都是通过该指针去访问。
- 每一个非静态成员函数中,都有一个this指针
- 是一个成员函数的形参,对象中不存储this指针
- this指针时成员函数第一个隐含的指针形参
- this指针类型:类类型*const this
- 只能在“成员函数”内部使用
class Date
{
public:
void Display()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
void SetDate(int year, int month, int day)
{
this->_year = year;
_month = month;
_day = day;
}
private:
int _year;
int _month;
int _day;
};