谈对象系列:C++类和对象

一、类的定义

1.1类定义的格式

使用class关键字,定义类,calssName是类名,{}中为类的主体,最后的分号 ;可别忘了加上。

类的名称,就是类的类型

  • 类定义的函数,属于inline内联函数,但具体展开还是得看编译器的选择。
class calssName
{
    //成员函数 
    
	//成员变量
};
int main()
{
    tag st1;//类名,就是类型
}

成员变量(member)的特殊标识:

  1. 在变量名前加上下划线
  2. 在变慢名前加上字母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+

评论 85
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值