目录
类的引入
C语言结构体中只能定义变量,在C++中,结构体内不仅可以定义变量,也可以定义函数。比如: 之前在数据结构初阶中,用C语言方式实现的栈,结构体中只能定义变量;现在以C++方式实现, 会发现struct中也可以定义函数。
class Stack
{//成员变量
public:
int* _a;
int _top;
int _capacity;
//成员函数
public:
void Init();
void Push(int x)
{
_a[_top] = x;
_top++;
}
};
类的定义
C++中类关键字有两个:struct和class。
C++兼容C,在C++中struct升级成了类。
类定义的两种方式:1.声明和定义全放在类中
class Stack
{//成员变量
public:
int* _a;
int _top;
int _capacity;
//成员函数
public:
void Init()
{
_a = (int*)malloc(sizeof(int) * 4);
_top = 0;
_capacity = 4;
}
void Push(int x)
{
_a[_top] = x;
_top++;
}
};
2. 类声明放在.h文件中,成员函数定义放在.cpp文件中
类定义了一个新的作用域。
在类体外定义成员时,需要使用 :: 作用域操作符指明成员属于哪个类域。
//如果成员函数放在类外定义要加::修饰找到类
class Stack
{//成员变量
public:
int* _a;
int _top;
int _capacity;
//成员函数
public:
void Init();
void Push(int x);
};
void Stack::Init()
{
_a = (int*)malloc(sizeof(int) * 4);
_top = 0;
_capacity = 4;
}
void Stack::Push(int x)
{
_a[_top] = x;
_top++;
}
类的访问
类有三种访问限定符,public(公有),private(私有),protected(受保护的)。
除了public外,其他访问限定符均不能在类外被访问!
struct默认访问限定符为public,而class默认访问限定符为private!
struct Student1
{//默认public
char name[10];
int age;
int id;
};
class Student2
{//默认private
char name[10];
int age;
int id;
};
int main()
{
Student1 s1;
strcpy_s(s1.name, "张三");
s1.age = 10;
s1.id = 1;
cout << s1.name << endl;
cout << s1.age << endl;
cout << s1.id << endl;
Student2 s2;//不能在类外访问成员变量
s2.age = 20;//这是不能执行的操作!
}
类的存储
类中只保存成员变量!成员函数位于公共代码区,不存储于类!
类的对象大小计算
既然类中不保存成员函数,那么类对象大小只要考虑成员变量。
结论:一个类的大小,实际就是该类中”成员变量”之和,当然要注意内存对齐!
内存对齐规则与结构体一致!
class A1 {
public:
void f1() {}
private:
int _a;
char _ch;
};
// 类中仅有成员函数
class A2 {
public:
void f2() {}
};
// 类中什么都没有---空类
class A3
{
};
A1大小为8,A2 A3均为1。
总结:没有成员变量的类对象,编译会给他们分配1byte占位,表示对象存在过。
this指针
C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量” 的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来传递,编 译器自动完成。
this指针特性
1. this指针的类型:类型* const,即成员函数中,不能给this指针赋值。(有时可以为空)
2. 只能在“成员函数”的内部使用
3. this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给 this形参。所以对象中不存储this指针。
4. this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传 递,不需要用户传递
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
//实质:this->_year
_month = month;
//this->_year
_day = day;
//this->_day
}
void Print()
{
cout <<_year<< "-" <<_month << "-"<< _day <<endl;
//this->_year this->_month this->_day
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
注:
this指针可以为空,但不能对空指针解引用!
this指针是形参,所以保存在栈区,不保存在类,类只保存成员变量!