C++数据结构(一)——一个简单的例子快速理解C++类

本文通过IntCell类的声明和实现,展示了C++中的类构造、成员函数、封装以及初始化列表的使用。类提供了read和write函数来访问和修改私有变量storedValue,同时强调了explicit关键字防止隐式类型转换。此外,还介绍了接口与实现分离的原则,分别在IntCell.h和IntCell.cpp中定义和实现类的功能。在main.cpp中,演示了如何创建并操作IntCell对象。
摘要由CSDN通过智能技术生成

类的声明

C++类由成员构成,成员既可以是变量也可以是函数

构建一个IntCell类举例

class IntCell{
	public:
		IntCell()
		{
			storedValue=0;
		} 
		IntCell(int initialValue)
		{
			storedValue = initialValue;
		}
		int read()
		{
			return storedValue;
		}
		void write(int x)
		{
			storedValue=x;
		} 
	private:
		int storedValue;
};

其中private表明storedValue是私有变量,对外不可见(透明)

一种更简洁的方式

class IntCell
{
	public:
		explicit IntCell(int initialValue=0)
		:storedValue(initialValue){}
		int read() const
		{
			return storedValue;
		}
		void write(int x)
		{
			storedValue = x;
		}
	private:
		int storedValue;
};

IntCell中的构成函数中使用了默认值,如果构建IntCell类对象时没有传入参数storedValue会默认为0

第五行为初始化列表,可以直接初始化数据成员, 当数据成员具有复杂初始化过程的类类型时可以节省很多时间;在数据成员为const情况下意味着对象在构建之后就不能够被修改,那么数据成员的值只能在初始化列表中进行初始化

IntCell的构造函数是explicit,所有的单参数构造函数都必须是explicit以避免后台的类型转换

只检测但是不改变对象状态的成员函数为访问函数,如IntCell中的read函数;改变状态的是修改函数,如IntCell中的write函数

类函数调用示例

#include<iostream>

using namespace std;

/*class IntCell{
	public:
		IntCell()
		{
			storedValue=0;
		} 
		IntCell(int initialValue)
		{
			storedValue = initialValue;
		}
		int read()
		{
			return storedValue;
		}
		void write(int x)
		{
			storedValue=x;
		} 
	private:
		int storedValue;
};
*/

class IntCell
{
	public:
		explicit IntCell(int initialValue=0)
		:storedValue(initialValue){}
		int read() const
		{
			return storedValue;
		}
		void write(int x)
		{
			storedValue = x;
		}
	private:
		int storedValue;
};
int main(){
	IntCell m, n(6);
	cout<<m.read()<<endl;
	cout<<n.read()<<endl;
	m.write(5);
	n.write(7);
	cout<<m.read()<<endl;
	cout<<n.read()<<endl;
	return 0;
} 

接口与实现分离

假设我们在IntCell.h中提供接口,在IntCell.cpp进行实现,在main.cpp使用

IntCell.h代码

#ifndef IntCell_H
#define IntCell_H

class IntCell
{
	public:
		explicit IntCell(int initialValue = 0);
		int read() const;
		void write(int x);
	private:
		int storedValue;
};

#endif

在文件开始时先要确认符号IntCell_H没有被定义(#ifndef),如果以及被定义则什么都不做,如果没有被定义则进行定义

IntCell.cpp代码

#include"IntCell.h" 

IntCell::IntCell(int initialValue):storedValue(initialValue)
{
}

int IntCell::read() const
{
	return storedValue;
}

void IntCell::write(int x)
{
	storedValue = x;
}

main.cpp代码

#include<iostream>
#include"IntCell.h"

using namespace std;

int main(){
	IntCell m, n(6);
	cout<<m.read()<<endl;
	cout<<n.read()<<endl;
	m.write(5);
	n.write(7);
	cout<<m.read()<<endl;
	cout<<n.read()<<endl;
	return 0;
} 
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾醒(AiXing-w)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值