【问题标题】:Can enclosing class access nested class?封闭类可以访问嵌套类吗?
【发布时间】:2021-11-06 21:01:02
【问题描述】:

我有以下代码:

#include <iostream>
#include <string>

class enclose
{
    private:
        int x;
    public:
        enclose(void) { x = 10; };
        ~enclose(void) { };

        class nested1
        {
            public:
                void printnumber(enclose p);
        };
};

void    enclose::nested1::printnumber(enclose p)
{
    std::cout << "the number is " << p.x << std::endl;
}

int main()
{
    enclose example;

    example.printnumber();
}

我知道最后一行 example.printnumber(); 不正确。但是,我想知道封闭类是否可以访问嵌套类的函数。 example如何访问printnumber()函数?

【问题讨论】:

    标签: c++ nested inner-classes


    【解决方案1】:

    封闭类可以访问嵌套类吗?

    是的,如果封闭类有嵌套类的实例(一个对象)。

    一个类是一个类是一个类...嵌套没关系,你必须总是有一个类的实例才能调用(非静态)成员函数。

    【讨论】:

    • 从 C++11 开始发生了变化。嵌套类可以访问封闭类的受保护成员和私有成员。 (stackoverflow.com/questions/5013717/…)。但是是的,嵌套类必须首先访问封闭的实例。 (例如对封闭类实例的引用)
    • @PKramer 哦不知道。答案已更新。
    猜你喜欢
    • 1970-01-01
    • 2011-01-14
    • 2023-03-29
    • 2015-07-16
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多