c++ - 如何在派生类中定义内部类成员?

标签 c++

#include<iostream>
using namespace std;
class A{
    public:
        class B{
            public:
                void fun1();
        };
};

class C:public A{
    public:
        B::fun1(){ // This line gives Error:can not define member function B::fun1() in C

        }       
};
int main(){
    C ob;
    return 0;
}

有什么方法可以在派生类中定义内部类成员吗? 此错误背后的原因是什么?

最佳答案

问题是您试图在与声明该函数的类作用域不同的类作用域内定义该函数。例如,考虑一下代码的扩展版本:

class A{
    public:
        class B{
            public:
                void fun1();
                void fun2();
        };

        void fun3();

        void B::fun2() {} // Error.
};

class C:public A{
    public:
        void B::fun1() {} // Error.
        void A::fun3() {} // Error.
};

所有三个错误都会给出相同类型的错误消息“Can not define member function X::Y() in Z”。


要解决这个问题,如果 A::B::fun1()C::B::fun1()需要有不同的实现,您也可以从嵌套类派生。

class A {
  public:
    class AB_ {
      public:
        virtual void fun1();
    };

    typedef AB_ B;
};
void A::AB_::fun1() {}

class C : public A {
  public:
    class CB_ : public A::AB_ {
        void fun1() override;
    };

    typedef CB_ B;
};
void C::CB_::fun1() {}

在这种情况下,您可以使用 B从外部访问嵌套类的最派生版本,或使用 A::AB_C::CB_直接地。同样,你可以这样写:

class A {
    class AB_ {
      public:
        virtual void fun1();
    } b;

  public:
    typedef AB_ B;

    virtual B& getB() { return b; }
};
void A::AB_::fun1() {}

class C : public A {
    // Note the use of the typedef, instead of the actual type name.
    class CB_ : public A::B {
        void fun1() override;
    } cb;

  public:
    typedef CB_ B;

    // Note the use of the typedef, instead of the actual type name.
    A::B& getB() override { return cb; }
};
void C::CB_::fun1() {}

在本例中,C内部使用A的 typedef,同时替换它;因此,使用 A的 typedef 变得明确,如 A::B而不是B 。由于 typedef 的原因,名称 B意味着 A::AB_C::CB_ ,当用作 A::B 时或C::B ,分别。

// If given the above...

int main() {
    std::cout << "A::B: " << typeid(A::B).name() << std::endl;
    std::cout << "C::B: " << typeid(C::B).name() << std::endl;
}

输出将是:

// GCC:
A::B: N1A3AB_E
C::B: N1C3CB_E

// MSVC:
A::B: class A::AB_
C::B: class C::CB_

关于c++ - 如何在派生类中定义内部类成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38110286/

相关文章:

c++ - 在 Win32 中确定按键和按键的最快方法是什么?

c++ - CCriticalSection 是做什么的?

c++ - 如何从连接的 ssl session 中获取 base64 编码证书 (PEM)

c++ - 使用 lua_pcall 调用的 lua 函数丢失的错误消息

c++ - 分配给 std::tie 和引用元组有什么区别?

c++ - C++ & 和 * 运算符在所有上下文中都是逆运算吗?

c++ - 如何使用 Rcpp 将映射<double,T> 从 C++ 传递到 R

c++ - 读取文件 ".txt"并将每一行的数据分配给循环列表中的新节点 C++

c++ - 为什么我的 map 的第二个值没有修改?

c++ - .begin 左边必须有类/结构/union