文章目录
一、类的定义
1.1类定义的格式
使用class关键字,定义类,calssName是类名,{}中为类的主体,最后的分号 ;
可别忘了加上。
类的名称,就是类的类型。
- 类定义的函数,属于inline内联函数,但具体展开还是得看编译器的选择。
class calssName
{
//成员函数
//成员变量
};
int main()
{
tag st1;//类名,就是类型
}
成员变量(member)的特殊标识:
- 在变量名前加上下划线
- 在变慢名前加上字母m
类的两种定义方法
将函数的定义和声明放在类里面实现:
这里使用class定义了一个日期类,在main函数里声明了一个day1对象,使用点操作符(.)
、箭头操作符 (->)
来访问类成员函数。
#include <iostream>
using std::cout;
using std::endl;
class Data
{
public:
void Init(int year = 2024, int month = 6, int day = 6)
{
_year = year;
_month = month;
_day = day;
}
void print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Data day1;
day1.Init(2024, 5, 20);
day1.print();
return 0;
}
将函数声明放在类里面,函数定义在类外面实现。
stack.h
#include <iostream>
class Stack
{
public:
void Init(int capacity = 4);
void Push(int x);
void Pop();
int Top();
int Empty();
void Destry()
{
assert(_next);
if (_next)
free(_next);
_next = NULL;
_top = 0;
_capacity = 0;
}
private:
int _top;
int _capacity;
int* _next;
};
stack.cpp
void Stack::Init(int capacity)
{
_next = (int*)malloc(sizeof(int) * capacity);
_top = 0;
_capacity = capacity;
}
void Stack::Push(int x)
{
if (_top == _capacity)
{
int newcapacity = _capacity == 0 ? 4 : _capacity * 2;
int* newNext = (int*)realloc(_next, sizeof(int) * newcapacity);
if (newNext == NULL)
{
perror("realloc fail");
exit(1);
}
_next = newNext;
_capacity = newcapacity;
}
_next[_top++] = x;
}
void Stack::Pop()
{
assert(_next && _top > 0);
_top--;
}
int Stack::Top()
{
assert(_next && _top > 0);
return _next[_top - 1];
}
int Stack::Empty()
{
return _top == 0;
}
结构体:
在C+