当前位置: 首页 > article >正文

C++学习笔记----8、掌握类与对象(五)---- 嵌套类与类中枚举

1、嵌套类

        类定义中不仅仅可以包含成员函数与数据成员。也可以包含嵌套类与struct,类型别名,以及枚举。在类中声明的任何东西都在类范围内。如果它是public,可以通过className::的范围解析语法来在类外进行访问。

        可以在另一个类定义中提供一个类定义。例如,你可能决定 让SpreadsheetCell类成为Spreadsheet类的一部分。由于它变成了Spreadsheet类的一部分,你可能也会重新将其命名为Cell。可以将它们定义成这样子:

export class Spreadsheet
{
public:

	class Cell
	{
	public:
		Cell() = default;
		Cell(double initialValue);
        // Remainder omitted for brevity
	};

	Spreadsheet(std::size_t width, std::size_t height,
		const SpreadsheetApplication& theApp);
    // Remainder of Spreadsheet declarations omitted for brevity
};

        现在,Cell类定义在了Spreadsheet类的内部,所以在Spreadsheet类之外对Cell的任何动作,必须给出Spreadsheet::的范围名。即使对于成员函数定义也一样。例如,Cell的double构造函数看起来像这样:

Spreadsheet::Cell::Cell(double initialValue)
	: m_value { initialValue }
{
}

        甚至对于Spreadsheet类自身的成员函数的返回类型(不是参数)也要使用这个语法:

const Spreadsheet::Cell& Spreadsheet::getCellAt(size_t x, size_t y) const
{
	verifyCoordinate(x, y);
	return m_cells[x][y];
}

        在Spreadsheet类内部直接完整地定义嵌套Cell类舍不得Spreadsheet类定义有一点儿臃肿。可以通过只包含一个Spreadsheet类的Cell的前向声明来简化,然后对Cell类进行单独定义,如下:

export class Spreadsheet
{
public:
    class Cell;
    Spreadsheet(std::size_t width, std::size_t height,
    const SpreadsheetApplication& theApp);
    // Remainder of Spreadsheet declarations omitted for brevity
};

class Spreadsheet::Cell
{
public:
    Cell() = default;
    Cell(double initialValue);
    // Omitted for brevity
};

2、类中枚举

        枚举也可以成为类中的数据成员。例如,可以添加SpreadsheetCell类的cell颜色如下:

export class SpreadsheetCell
{
public:
	// Omitted for brevity
	enum class Color { Red = 1, Green, Blue, Yellow };
	void setColor(Color color);
	Color getColor() const;

private:
	// Omitted for brevity
	Color m_color{ Color::Red };
};

        setColor()与getColor()成员函数的实现很直接:

void SpreadsheetCell::setColor(Color color) { m_color = color; }
SpreadsheetCell::Color SpreadsheetCell::getColor() const { return m_color; }

        新的成员函数使用如下:

SpreadsheetCell myCell { 5 };
myCell.setColor(SpreadsheetCell::Color::Blue);
auto color { myCell.getColor() };

http://www.kler.cn/news/336387.html

相关文章:

  • unity 介绍Visual Scripting Scene Variables
  • 在线教育系统开发:SpringBoot技术实战
  • 【C++】入门基础介绍(下)输入输出,函数重载,缺省与引用
  • 【深度学习基础模型】稀疏自编码器 (Sparse Autoencoders, SAE)详细理解并附实现代码。
  • 服务器数据恢复—OneFS文件系统下数据被删除的数据恢复案例
  • ad.concat()学习
  • 微信小程序开发-配置文件详解
  • C++之模版进阶篇
  • 【二十九】【QT开发应用】初步认识QSS,字体样式,边框样式,边框圆角,文字位置,背景样式,动态悬浮样式
  • Vue2电商项目(八) 完结撒花:图片懒加载、路由懒加载、打包的map文件
  • SpringBoot 集成 Ehcache 实现本地缓存
  • C嘎嘎入门篇:类和对象番外(时间类)
  • css如何制作瀑布流
  • 1、如何查看电脑已经连接上的wifi的密码?
  • 第三届图像处理、计算机视觉与机器学习国际学术会议(ICICML 2024)
  • jetbrains ide重命名问题
  • 《基于多视角深度学习技术的乳腺X线分类:图网络与Transformer架构的研究》|文献速递-基于多模态-半监督深度学习的病理学诊断与病灶分割
  • RabbitMQ入门1—queue参数之type
  • Flutter 3.24 AAPT: error: resource android:attr/lStar not found.
  • ②EtherCAT转ModbusTCP, EtherCAT/Ethernet/IP/Profinet/ModbusTCP协议互转工业串口网关