【发布时间】:2013-10-29 15:19:06
【问题描述】:
我在实现工厂方法的一些变体时遇到了问题。
// from IFoo.h
struct IFoo {
struct IBar {
virtual ~IBar() = 0;
virtual void someMethod() = 0;
};
virtual IBar *createBar() = 0;
};
// from Foo.h
struct Foo : IFoo { // implementation of Foo, Bar in Foo.cpp
struct Bar : IBar {
virtual ~Bar();
virtual void someMethod();
};
virtual Bar *createBar(); // implemented in Foo.cpp
};
我想在Foo.cpp 中声明 Foo::Bar。现在我不能成功:
struct Foo : IFoo {
//struct Bar; //1. error: invalid covariant return type
// for ‘virtual Foo::Bar* Foo::createBar()’
//struct Bar : IBar; //2. error: expected ‘{’ before ‘;’ token
virtual Bar *createBar();
// virtual IBar *createBar(); // Is not acceptable by-design
};
在Foo.hpp 中仅前向声明Boo 并在Foo.cpp 中进行完整声明是否有技巧?
编辑: 看起来,我没有清楚地显示错误。所以,有更详细的示例。
-
前向声明的第一次尝试:
struct Foo : IFoo { struct Bar; virtual Bar *createBar(); //<- Compile-error }; //error: invalid covariant return type for ‘virtual Foo::Bar* Foo::createBar()’ -
前向声明的第二次尝试:
struct Foo : IFoo { struct Bar : IBar; //<- Compile-error virtual Bar *createBar(); }; // error: expected ‘{’ before ‘;’ token -
有人可以提议更改
createBar的返回类型(从Bar到IBar)struct Foo : IFoo { virtual IBar *createBar(); };但是,这种解决方法在设计上是不可接受的
【问题讨论】:
-
谢谢。修改后可以吗?
标签: c++ inheritance compiler-errors inner-classes forward-declaration