【问题标题】:How to instantiate a nested class given an instance of the containing class如何在给定包含类的实例的情况下实例化嵌套类
【发布时间】:2014-01-02 19:45:45
【问题描述】:

是否可以这样做:

class BaseClass
{
public:
    class NestedClass
    {
    };
};

BaseClass foo;
foo.NestedClass bar;

如何从实例中获取类型?

【问题讨论】:

  • 什么意思:I would like it to work with multiple classes containing the same nested class name
  • 例如,如果我有包含 NestedClass 的 BaseClass2
  • 问题含混不清,没有表现出真正的意图(设计目标)
  • 是的,问题不清楚
  • 对不起,我不是英语,但我正在寻找的答案在我的答案中。

标签: c++ types instance nested-class


【解决方案1】:

你需要做的是:

BaseClass::NestedClass bar;

您无法避免使用范围解析运算符,但您可以在适当的范围内将typedef 作为简写:

typedef BaseCLass::NestedClass NestedClass;

编辑: 根据问题的变化,如果您想要实例中的类型,在 c++11 中您可以使用 decltype:

decltype(foo)::NestedClass;

但这毫无意义,因为decltype 在这种情况下会返回 BaseClass。

【讨论】:

  • 你确定没有别的办法吗?
  • 相当肯定。为什么不想要范围解析或 typedef?
  • 只是因为它在 C# 中工作,我想知道在 C++ 中是否可行。
  • 可能有点无意义,但只要我改变foo的类型,它仍然有效。
【解决方案2】:

您将范围解析运算符与基类名称一起使用:

BaseClass::NestedClass bar;

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2015-08-27
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多