c++是基于面向对象的,关注的是对象
在C语言中,结构体只能够定义变量,但是在c++中,结构体不仅可以定义变量,还可以定义函数
比如:
typedef int DataType;
struct Stack
{
void Init(size_t capacity)
{
_array = (DataType*)malloc(sizeof(DataType) * capacity);
if (nullptr == _array)
{
perror("malloc申请空间失败");
return;
}
_capacity = capacity;
_size = 0;
}
void Push(const DataType& data)
{
// 扩容
_array[_size] = data;
++_size;
}
DataType Top()
{
return _array[_size - 1];
}
void Destroy()
{
if (_array)
{
free(_array);
_array = nullptr;
_capacity = 0;
_size = 0;
}
}
DataType* _array;
size_t _capacity;
size_t _size;
};
int main()
{
Stack s;
s.Init(10);
s.Push(1);
s.Push(2);
s.Push(3);
cout << s.Top() << endl;
s.Destroy();
return 0;
}
在c++中,上面的结构体的定义更喜欢使用class来代替
class zyyname
{
//类体
};
1.上述代码中
class
为定义类的关键字,zyyname
是类的名字,{}
中为类的主体
2.这里我们要注意的是,类体
是有成员变量和成员函数组成的,在括号后面一定要加分号
类体中内容称为类的成员,类中的变量称为类的属性或成员变量,类中的函数称为类的方法或者成员函数
声明和定义全部放在类体中
这里需注意:成员函数如果在类中定义,编译器可能会将其当成内联函数处理。
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
//只是声明
int _year;
int _month;
int _day;
};
类声明放在.h文件中,成员函数定义放在.cpp文件中,注意
:成员函数名前需要加类名::
.h头文件中
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
private:
//只是声明
int _year;
int _month;
int _day;
};
.cpp文件中
void Date::Init()
{
cout << _year << "-" << _month << "_" << _day << endl;
}
int main()
{
Date d1;
d1.Init();
return 0;
}
C++实现封装的方式:用类将对象的属性与方法结合在一块,让对象更加完善,通过访问权限选择性的将其接口提供给外部的用户使用
访问限定符有:public(公有),protected(保护),private(私有)
这里解释一下访问限定符:
1.public修饰的成员类可以直接访问
2. protected和private修饰的成员在类外不能直接被访问
3.访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止
4.如果后面没有访问限定符,作用域就到 } 即类结束。
5.class的默认访问权限为private,struct为public
类定义了一个新的作用域,类的成员都在类的作用域中,在类体外定义的成员需要使用的时候需要用
::
作用域操作符指明成员属于哪个类
class Person
{
public:
void PrintPersonInfo();
private:
char _name[20];
char _gender[3];
int _age;
};
// 这里需要指定PrintPersonInfo是属于Person这个类域
void Person::PrintPersonInfo()
{
cout << _name << " "<< _gender << " " << _age << endl;
}
什么叫做类的实例化:就是用类这个类型创建对象的过程,称作为实例化
这里我们定义一个类
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout <<_year<< "-" <<_month << "-"<< _day <<endl;
}
private:
int _year; // 年
int _month; // 月
int _day; // 日
};
int main()
{
Date d1, d2;
d1.Init(2024,2,2);
d2.Init(2024, 1, 2);
d1.Print();
d2.Print();
return 0;
}
上面的类中有Init和Print两个成员函数
C++编译器给每个“非静态的成员函数“增加了一个隐藏
的指针参数,让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量”的操作,都是通过该指针去访问。只不过所有的操作对用户是透明的,即用户不需要来递,编译器自动完成。
1.this指针的类型:类 类型中*const,也就是说成员函数中,不可以给this指针赋值
2.只可以在成员函数的内部使用
3.this指针本质上是成员函数的形参,当对象调用成员函数时,将对象地址作为实参传递给
this形参
4.this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传
递,不需要用户传递
下面我们看几个代码来解释一下
class A
{
public:
void Print()
{
cout << "Print()" << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print();
return 0;
}
这段代码是会正常运行的,因为p->PrintA()
只需要作为实参传递给this指针
最后说一下,this指针是存在 栈区,this是一个形参