如何在派生类中定义内部类成员
How to define inner class member in derived class?
#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
的类型定义的使用是显式的,作为A::B
而不是B
。由于类型的不同,名称B
在分别用作A::B
或C::B
时将表示A::AB_
或C::CB_
。
// 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_
相关文章:
- 在设计 SDK 时,我是否应该在 C++ 头文件中完全隐藏内部类?
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 从内部类继承
- 如何将枚举类转发声明为模板化类的内部类?
- 从内部类中的方法从包含类调用方法
- 从模板化父类中的派生内部类访问受保护的成员变量
- C++模板类的内部类访问
- 可视化C++外部定义内联函数
- 使用类模板的内部类模板专用化模板
- 参数化类的别名(或类型定义)内部类
- 如何在外部类中使用类模板时定义内部类构造函数
- 为什么内部类*定义*不能使用其父类?
- C++ 定义内部类的<<运算符
- 外部类的嵌套类定义,而外部类包含内部类的实例
- 在命名空间中,如何定义从内部类返回对象的函数
- 如何在不把内部类的定义放入父类的情况下创建一个内部类
- 扩展非类型形参包来定义带有非类型形参的内部类模板是否合法?
- 模板类外部的内部类方法定义
- 使用(非类型)枚举参数定义内部类成员函数模板
- 如何在派生类中定义内部类成员