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

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 brevityenum class Color { Red = 1, Green, Blue, Yellow };void setColor(Color color);Color getColor() const;private:// Omitted for brevityColor 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.mrgr.cn/news/44492.html

相关文章:

  • 推荐系统中的协同过滤
  • 【MySQL】--数据类型
  • Spring Boot框架在医院管理中的应用
  • Docker 实践与应用举例
  • @KafkaListener注解中containerFactory属性的作用
  • Arthas match Elasticsearch
  • 深入理解 Spring Cache 的工作原理及集成其它第三方缓存
  • 手把手教你集成GraphRag.Net:打造智能图谱搜索系统
  • 大模型面试宝典:问题全集及权威解答
  • 你真的了解Elecron吗?
  • 面试官:如何实现分布式系统的限流?
  • ‌图片编辑为底片,智能工具助力,创作精彩视觉作品
  • 影刀RPA实战:Excel排序、替换与格式
  • 超强AI绘画工具StableDiffusion,SD整合包V4.9 来了 版本win加mac安装包以及搭载PS安装说明
  • 基于springboot vue 研究生科研文档资料管理系统设计与实现
  • 产品经理内容分享(二):AI产品经理的入门路线图
  • SpringBoot企业级开发(SpringSecurity安全控制+pringBatch批处理+异步消息+系统集成SpringIntegration)
  • 利用LLMs自动寻找量化投资策略
  • 医院管理新趋势:Spring Boot技术引领
  • 安卓如何实现双击触摸唤醒点亮屏幕功能-Android framework实战开发