c++ - C++ 中的嵌套类

标签 c++

我有

class outer: public base
{
public:
 class inner
 {
   foo();
 }
}
  1. 如何初始化这些嵌套类?
  2. 我可以从外部类调用 foo() 吗?
  3. 你能告诉我在嵌套类和访问成员时我应该知道的经验法则是什么吗? 谢谢

最佳答案

我猜你是从 java 过来的。

C++ 嵌套结构/类就像 java static 嵌套类型。它与包含类型没有实例关系。

事实上,除了可能需要将之前的内部类标记为外部类的友元之外,您应该能够将内部类移动到包含命名空间的命名空间。

演示见http://ideone.com/ddjGX

  1. How do i initialize these nested class?

你不知道。您只能初始化成员(类实例)

  1. Can I call foo() from the outer class?

除非你是 friend 或方法 (foo()) 是公开的

  1. Can you please tell me what is the thumb rule I should know while nesting class and accessing the members?

只有在以下情况下我才会选择嵌套类型

  1. 类型是一个实现细节或取决于外部类
  2. 从外部类共享静态成员(枚举、typedef、模板参数、静态方法和字段)的便利性:内部类隐式地是外部类的 friend

我在下面说明了这些“经验法则”。请注意嵌套类型如何透明地访问外部类的私有(private)成员。


struct base {};

class outer: public base
{
  private:
    enum { some=42, special=67, implementation=999, details=-13 };

  public:
    struct inner 
    { 
      protected: 
        void foo() { int can_usethis = special + implementation + details; } 
    };

    outer() : _inner() { }

    void call_inner(inner& i) const 
    { 
        //i.foo(); // fails (protected)
    }

    void call_inner() const 
    { 
        //_inner.foo(); // fails (protected)
    }

  private:
    inner _inner;
};


int main()
{
    outer o;
    outer::inner i;

    // i.foo(); // fails: protected
    o.call_inner(i);
}

关于c++ - C++ 中的嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7974057/

相关文章:

c++ - 为什么 lambda 会减慢排序速度

c++ - 使用外部 C 库在 Rcpp 中编译 C++

c++ - 基于 Boost spirit 语法的字符串拆分

c++ - 不绘制 OpenGL 的纹理

c++ - 为什么我的指针输出一个字符串而不是 C++ 中的内存地址?

c++ - 为什么整数类型 int64_t 不能持有这个合法值?

c++ - 如何通过 boost::asio 和 shared_ptr 创建串口

c++ - 在 Visual Studio 的 C++ 项目中是否可以使用宏来识别当前的 SOLUTION 配置?

c++ - 在运行时确定对象类型的最佳方法

c++ - 通过引用修改数组后,为什么它保持不变?