当前位置: 首页 > 编程日记 > 正文

C++中嵌套类的使用

一个类可以定义在另一个类的内部,前者称为嵌套类(nested class)或嵌套类型(nested type)。嵌套类常用于定义作为实现部分的类。嵌套类可用于隐藏实现细节。

嵌套类是一个独立的类,与外层类基本没什么关系。特别是,外层类的对象和嵌套类的对象是相互独立的。在嵌套类的对象中不包含任何外层类定义的成员;类似的,在外层类的对象中也不包含任何嵌套类定义的成员。

嵌套类的名字在外层类作用域中是可见的,在外层类作用域之外不可见。和其它嵌套的名字一样,嵌套类的名字不会和别的作用域中的同一个名字冲突。

嵌套类中成员的种类与非嵌套类是一样的。和其它类类似,嵌套类也使用访问限定符来控制外界对其成员的访问权限。外层类对嵌套类的成员没有特殊的访问权限,同样,嵌套类对外层类的成员也没有特殊的访问权限。

嵌套类在其外层类中定义了一个类型成员。和其它成员类似,该类型的访问权限由外层类决定。位于外层类public部分的嵌套类实际上定义了一种可以随处访问的类型;位于外层类protected部分的嵌套类定义的类型只能被外层类及其友元和派生类访问;位于外层类private部分的嵌套类定义的类型只能被外层类的成员和友元访问。

嵌套类必须声明在类的内部,但是可以定义在类的内部或者外部。当我们在外层类之外定义一个嵌套类时,必须以外层类的名字限定嵌套类的名字。在嵌套类在其外层类之外完成真正的定义之前,它都是一个不完全类型。

嵌套类和外层类是相互独立的:尽管嵌套类定义在其外层类的作用域中,但是外层类的对象和嵌套类的对象没有任何关系。嵌套类的对象只包含嵌套类定义的成员;同样,外层类的对象只包含外层类定义的成员,在外层类对象中不会有任何嵌套类的成员。

在C++11之前,嵌套类仅仅可以使用外层类的类型名、静态成员和枚举类型。但在C++11中,遵循非静态成员的通用使用规则,嵌套类可以使用外层类的任何成员。

下面是从其他文章中copy的测试代码,详细内容介绍可以参考对应的reference:

#include "nested_class.hpp"
#include <iostream>
#include <vector>
#include <typeinfo>namespace nested_class_ {
//
// reference: http://en.cppreference.com/w/cpp/language/nested_types
int x, y; // globals
class enclose { // enclosing classint x; // note: private membersstatic int s;
public:struct inner { // nested classvoid f(int i) {//x = i; // Error: can't write to non-static enclose::x without instance//int a = sizeof(x); // Error until C++11,// OK in C++11: operand of sizeof is unevaluated,// this use of the non-static enclose::x is allowed.s = i;   // OK: can assign to the static enclose::s::nested_class_::x = i; // OK: can assign to global xy = i;   // OK: can assign to global y}void g(enclose* p, int i) {p->x = i; // OK: assign to enclose::x}};
};class enclose_ {struct nested { // private membervoid g() {}};
public:static nested f() { return nested{}; }
};int test_nested_class_1()
{//enclose_::nested n1 = enclose_::f(); // error: 'nested' is privateenclose_::f().g(); // OK: does not name 'nested'auto n2 = enclose_::f(); // OK: does not name 'nested'n2.g();return 0;
}// reference: http://www.sanfoundry.com/c-tutorials-nested-structure-access/
/* structure A declared */
typedef struct A {int a;float b;
} New_a;/* structure B declared */
typedef struct B {int c;float d;struct A e;    /* member 'e' is itself a structure */
} New_b;int test_nested_class_2()
{/* Let's declare variables of New_a and New_b */New_a bread;New_b butter;        /* 'butter' is a nested structure *//* Let's access bread using dot operator */bread.a = 10;        /* assigned member a value 10 */bread.b = 25.50;/* Let's access butter using dot operator */butter.c = 10;butter.d = 50.00;/* Let's access member 'e' which is a nested structure */butter.e.a = 20;butter.e.b = 20.00;/* Display values of members of 'butter.e' structure */printf("butter.e.a is %4d\n", butter.e.a);printf("butter.e.b is %.2f\n", butter.e.b);return 0;
}// reference: http://www.geeksforgeeks.org/nested-classes-in-c/
/* start of Enclosing class declaration */
class Enclosing {int x;/* start of Nested class declaration */class Nested {int y;void NestedFun(Enclosing *e) {std::cout << e->x;  // works fine: nested class can access// private members of Enclosing class}}; // declaration Nested class ends here
}; // declaration Enclosing class ends hereint test_nested_class_3()
{return 0;
}// reference: http://www.oopweb.com/CPP/Documents/CPPAnnotations/Volume/cplusplus16.html
class Clonable {
public:class Base {public:virtual ~Base() {}virtual Base *clone() const = 0;};private:Base *d_bp;public:Clonable() : d_bp(0) {}~Clonable() { delete d_bp; }Clonable(Clonable const &other) { copy(other); }Clonable &operator=(Clonable const &other){if (this != &other) {delete d_bp;copy(other);}return *this;}// New for virtual constructions:Clonable(Base const &bp){d_bp = bp.clone();      // allows initialization from}                           // Base and derived objectsBase &get() const{return *d_bp;}private:void copy(Clonable const &other){if ((d_bp = other.d_bp))d_bp = d_bp->clone();}
};class Derived1 : public Clonable::Base
{
public:~Derived1(){std::cout << "~Derived1() called\n";}virtual Clonable::Base *clone() const{return new Derived1(*this);}
};int test_nested_class_4()
{std::vector<Clonable> bv;bv.push_back(Derived1());std::cout << "==\n";std::cout << typeid(bv[0].get()).name() << std::endl;std::cout << "==\n";std::vector<Clonable> v2(bv);std::cout << typeid(v2[0].get()).name() << std::endl;std::cout << "==\n";return 0;
}/
// reference: http://www.sanfoundry.com/cpp-program-illustrate-nested-classes/
class Stack {class Node {public:int data;Node* next;Node(int data, Node* next);~Node();}*head;
public:Stack();Stack(const Stack& s);void operator=(const Stack& s);~Stack();void push(int data);int peek() const;int pop();
};Stack::Node::Node(int data, Node* next)
{this->data = data;this->next = next;
}Stack::Node::~Node() { }Stack::Stack() { head = NULL; }Stack::Stack(const Stack& s)
{head = s.head;
}void Stack::operator=(const Stack& s)
{head = s.head;
}void Stack::push(int data)
{head = new Node(data, head);
}int Stack::peek() const {if (head == 0) {std::cerr << "Stack empty!" << std::endl;return -1;}elsereturn head->data;
}int Stack::pop()
{if (head == NULL) return -1;int result = head->data;Node* oldNode = head;head = head->next;delete oldNode;return result;
}Stack::~Stack()
{if (head != NULL) {while (head->next != NULL) {Node* temp = head;head = head->next;delete temp;}}
}int test_nested_class_5()
{Stack Integers;int value, num;std::cout << "Enter the number of elements ";std::cin >> num;while (num > 0) {std::cin >> value;Integers.push(value);num--;}while ((value = Integers.pop()) != -1)std::cout << "Top element of stack  " << value << std::endl;return 0;
}//
// reference: https://msdn.microsoft.com/en-us/library/71dw8xzh.aspx
class X
{template <class T>struct Y {T m_t;Y(T t) : m_t(t) { }};Y<int> yInt;Y<char> yChar;public:X(int i, char c) : yInt(i), yChar(c) { }void print(){std::cout << yInt.m_t << " " << yChar.m_t << std::endl;}
};int test_nested_class_6()
{X x(1, 'a');x.print();return 0;
}///
// reference: https://msdn.microsoft.com/en-us/library/71dw8xzh.aspx
template <class T>
class X_
{template <class U>class Y {U* u;public:Y();U& Value();void print();~Y();};Y<int> y;
public:X_(T t) { y.Value() = t; }void print() { y.print(); }
};template <class T>
template <class U>
X_<T>::Y<U>::Y()
{std::cout << "X_<T>::Y<U>::Y()" << std::endl;u = new U();
}template <class T>
template <class U>
U& X_<T>::Y<U>::Value()
{return *u;
}template <class T>
template <class U>
void X_<T>::Y<U>::print()
{std::cout << this->Value() << std::endl;
}template <class T>
template <class U>
X_<T>::Y<U>::~Y()
{std::cout << "X_<T>::Y<U>::~Y()" << std::endl;delete u;
}int test_nested_class_7()
{X_<int>* xi = new X_<int>(10);X_<char>* xc = new X_<char>('c');xi->print();xc->print();delete xi;delete xc;return 0;
}} // namespace nested_class_

GitHub: https://github.com/fengbingchun/Messy_Test 

相关文章:

挑战弱监督学习的三大热门问题 AutoWSL2019挑战赛正式开赛

AutoWSL2019作为11月17-19日亚洲机器学习大会&#xff08;ACML&#xff09;主会议竞赛单元之一&#xff0c;由第四范式、ChaLearn、RIKEN和微软联合举办&#xff0c;其中竞赛分享和颁奖将与大会WSL-Workshop共同举办。据悉&#xff0c;AutoWSL是继AutoCV、AutoCV2、AutoNLP、Au…

数据连接池的工作机制是什么?

以典型的数据库连接池为例&#xff1a; 首先普通的数据库访问是这样的&#xff1a;程序和数据库建立连接&#xff0c;发送数据操作的指令&#xff0c;完成后断开连接。等下一次请求的时候重复这个过程&#xff0c;即每个请求都需要和数据库建立连接和断开连接&#xff0c;这样当…

apkplug插件托管服务简化与简介-05

2019独角兽企业重金招聘Python工程师标准>>> 本文基于TuoClondService1.1.0讲解 apkplug插件托管服务是提供给开发者一个远程发布插件的管理平台&#xff0c;但v1.0.0版本接口调用有些复杂我们在v1.1.0版本中着重对其进行了简化 与封装&#xff0c;使开发者能更简…

SpringBoot-JPA入门

SpringBoot-JPA入门 JPA就是Spring集成了hibernate感觉。 注解&#xff0c;方法仓库&#xff08;顾名思义的方法&#xff0c;封装好了&#xff0c;还有自定义的方法&#xff09;。 案例: spring:datasource:url: jdbc:mysql://localhost:3306/springboot?useUnicodetrue&c…

PCA、LDA、MDS、LLE、TSNE等降维算法的Python实现

整理 | 夕颜出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】网上关于各种降维算法的资料参差不齐&#xff0c;但大部分不提供源代码。近日&#xff0c;有人在 GitHub 上整理了一些经典降维算法的 Demo(Python)集合&#xff0c;同时给出了参考资料的链接。PCA…

C++11中enum class的使用

枚举类型(enumeration)使我们可以将一组整型常量组织在一起。和类一样&#xff0c;每个枚举类型定义了一种新的类型。枚举属于字面值常量类型。 C包含两种枚举&#xff1a;限定作用域的和不限定作用域的。这里主要介绍限定作用域的。不限定作用域的使用可以参考&#xff1a; ht…

Windows下Mysql主从配置(Mysql5.5)

主数据库IP:192.168.3.169从数据库IP:192.168.3.34主数据库配置my.inin&#xff1a;在[mysqld]下添加配置数据&#xff1a;server-id1 #配一个唯一的ID编号&#xff0c;1至32。log-binmysql-bin #二进制文件存放路径#设置要进行或不要进行主从复制的数据库名&#xff0c;同…

K-最近邻法(KNN) C++实现

关于KNN的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78464169 这里给出KNN的C实现&#xff0c;用于分类。训练数据和测试数据均来自MNIST&#xff0c;关于MNIST的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/deta…

AI大佬“互怼”:Bengio和Gary Marcus隔空对谈深度学习发展现状

编译 | AI科技大本营编辑部出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;去年以来&#xff0c;由于纽约大学教授 Gary Marcus 对深度学习批评&#xff0c;导致他在社交媒体上与许多知名的 AI 研究人员如 Facebook 首席 AI 科学家 Yann LeCun 进行了一场论战。不止 …

Centos7多内核情况下修改默认启动内核方法

1.1 进入grub.cfg配置文件存放目录/boot/grub2/并备份grub.cfg配置文件 [rootlinux-node1 ~]# cd /boot/grub2/ [rootlinux-node1 grub2]# cp -p grub.cfg grub.cfg.bak [rootlinux-node1 grub2]# ls -ld grub.cfg* -rw-r--r--. 1 root root 5162 Aug 11 2018 grub.cfg -rw-r…

TensorRT Samples: MNIST

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551以下是参考TensorRT 2.1.2中的sampleMNIST.cpp文件改写的实现对手写数字0-9识别的测试代码&#xff0c;各个文件内容如下&#xff1a;common.hpp:#ifndef FBC_TENSORRT_TE…

网红“AI大佬”被爆论文剽窃,Jeff Dean都看不下去了

作者 | 夕颜、Just出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09;【导读】近日&#xff0c;推特上一篇揭露 YouTube 网红老师 Siraj Raval 新发表论文涉抄袭其他学者的帖子引起了讨论。揭露者是曼彻斯特大学计算机科学系研究员 Andrew M. Webb&#xff0c;他在 Twit…

数位dp(求1-n中数字1出现的个数)

题意&#xff1a;求1-n的n个数字中1出现的个数。 解法:数位dp&#xff0c;dp[pre][now][equa] 记录着第pre位为now&#xff0c;equa表示前边是否有降数字&#xff08;即后边可不能够任意取&#xff0c;true为没降&#xff0c;true为已降&#xff09;&#xff1b;常规的记忆化搜…

TensorRT Samples: MNIST API

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleMNISTAPI.cpp文件改写的实现对手写数字0-9识别的测试代码&#xff0c;各个文件内容如下&#xff1a;common.hpp:#ifndef FBC_TENSORR…

免费学习AI公开课:打卡、冲击排行榜,还有福利领取

CSDN 技术公开课 Plus--AI公开课再度升级内容全新策划&#xff1a;贴近开发者&#xff0c;更多样、更落地形式多样升级&#xff1a;线上线下、打卡学习&#xff0c;资料福利&#xff0c;共同交流成长&#xff0c;扫描下方小助手二维码&#xff0c;回复&#xff1a;公开课&#…

Gamma阶段第一次scrum meeting

每日任务内容 队员昨日完成任务明日要完成的任务张圆宁#91 用户体验与优化&#xff1a;发现用户体验细节问题https://github.com/rRetr0Git/rateMyCourse/issues/91#91 用户体验与优化&#xff1a;发现并优化用户体验&#xff0c;修复问题https://github.com/rRetr0Git/rateMyC…

windows 切换 默认 jdk 版本

set JAVA_HOMEC:\jdk1.6.0u24 set PATH%JAVA_HOME%\bin;%PATH%转载于:https://www.cnblogs.com/dmdj/p/3756887.html

TensorRT Samples: GoogleNet

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleGoogleNet.cpp文件改写的测试代码&#xff0c;文件(googlenet.cpp)内容如下&#xff1a;#include <iostream> #include <t…

Visual Studio Code Go 插件文档翻译

此插件为 Go 语言在 VS Code 中开发提供了多种语言支持。 阅读版本变更日志了解此插件过去几个版本的更改内容。 1. 语言功能 (Language Features) 1.1 智能感知 (IntelliSense) 编码时符号自动补全&#xff08;使用 gocode &#xff09;编码时函数签名帮助提示&#xff08;使用…

资源 | 吴恩达《机器学习训练秘籍》中文版58章节完整开源

整理 | Jane出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;一年前&#xff0c;吴恩达老师的《Machine Learning Yearning》(机器学习训练秘籍&#xff09;中文版正式发布&#xff0c;经过一年多的陆续更新&#xff0c;近日&#xff0c;这本书的中文版 58…

js字符串加密的几种方法

在做web前端的时候免不了要用javascript来处理一些简单操作&#xff0c;其实如果要用好JQuery, Prototype,Dojo 等其中一两个javascript框架并不简单&#xff0c;它提高你的web交互和用户体验&#xff0c;从而能使你的web前端有非一样的感觉&#xff0c;如海阔凭鱼跃。当然&…

Vue开发入门看这篇文章就够了

摘要&#xff1a; 很多值得了解的细节。 原文&#xff1a;Vue开发看这篇文章就够了作者&#xff1a;RandomFundebug经授权转载&#xff0c;版权归原作者所有。 介绍 Vue 中文网Vue githubVue.js 是一套构建用户界面(UI)的渐进式JavaScript框架库和框架的区别 我们所说的前端框架…

TensorRT Samples: CharRNN

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的sampleCharRNN.cpp文件改写的测试代码&#xff0c;文件(charrnn.cpp)内容如下&#xff1a;#include <assert.h> #include <str…

Python脚本BUG引发学界震动,影响有多大?

作者 | beyondma编辑 | Jane来源 | CSDN博客近日一篇“A guide to small-molecule structure assignment through computation of (1H and 13C) NMR chemical shifts”文章火爆网络&#xff0c;据作者看到的资料上看这篇论文自身的结果没有什么问题&#xff0c;但是&#xff0c…

C++中public、protect和private用法区别

Calsspig : public animal,意思是外部代码可以随意访问 Classpig : protect animal ,意思是外部代码无法通过该子类访问基类中的public Classpig : private animal ,意思是告诉编译器从基类继承的每一个成员都当成private,即只有这个子类可以访问 转载于:https://blog.51cto.…

TensorRT Samples: MNIST(Plugin, add a custom layer)

关于TensorRT的介绍可以参考&#xff1a;http://blog.csdn.net/fengbingchun/article/details/78469551 以下是参考TensorRT 2.1.2中的samplePlugin.cpp文件改写的通过IPlugin添加一个全连接层实现对手写数字0-9识别的测试代码&#xff0c;plugin.cpp文件内容如下&#xff1a…

AutoML很火,过度吹捧的结果?

作者 | Denis Vorotyntsev译者 | Shawnice编辑 | Jane出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;【导语】现在&#xff0c;很多企业都很关注AutoML领域&#xff0c;很多开发者也开始接触和从事AutoML相关的研究与应用工作&#xff0c;作者也是&#…

tomcat6 配置web管理端访问权限

配置tomcat 管理端登陆 /apache-tomcat-6.0.35/conf/tomcat-users.xml 配置文件&#xff0c;使用时需要把注释去掉<!-- <!-- <role rolename"tomcat"/> <role rolename"role1"/> <user username"tomcat" password"…

@程序员:Python 3.8正式发布,重要新功能都在这里

整理 | Jane、夕颜出品 | AI科技大本营&#xff08;ID&#xff1a;rgznai100&#xff09;【导读】最新版本的Python发布了&#xff01;今年夏天&#xff0c;Python 3.8发布beta版本&#xff0c;但在2019年10月14日&#xff0c;第一个正式版本已准备就绪。现在&#xff0c;我们都…

TensorRT Samples: MNIST(serialize TensorRT model)

关于TensorRT的介绍可以参考&#xff1a; http://blog.csdn.net/fengbingchun/article/details/78469551 这里实现在构建阶段将TensorRT model序列化存到本地文件&#xff0c;然后在部署阶段直接load TensorRT model序列化的文件进行推理&#xff0c;mnist_infer.cpp文件内容…