C ++类方法,返回向量< subclass> [英] C++ class method, returns vector<subclass>
问题描述
我有一个麻烦的方法我试图写一个类。我有类符号和类终端。类终端扩展类符号,但类符号的方法之一需要返回向量。例如:
I'm having a bit of trouble with a method I'm trying to write for a class. I have class symbol and class terminal. class terminal extends class symbol, but one of the methods of class symbol needs to return a vector. E.g.:
#ifndef SYMBOL_H
#define SYMBOL_H
#include "terminal.h"
#include <vector>
using namespace std;
class symbol {
public:
vector<terminal> first();
virtual void polymorphable();
};
#endif
定义类终端:
#ifndef TERMINAL_H
#define TERMINAL_H
#include "symbol.h"
using namespace std;
class terminal: public symbol {
// ...
};
#endif
但是,这样做时,建立,其中一个或另一个首先在定义向量函数的行上的'terminal':undeclared identifier,以及在终端类定义的行上的'symbol':base class undefined。
However, when doing this, I get two errors when building, with one or the other coming first: "'terminal' : undeclared identifier" on the line that defines the vector function, and "'symbol' : base class undefined" on the line with the terminal class definition.
如何解决这个'需要b','b需要一个问题?
How do I solve this 'a requires b', 'b requires a' issue?
推荐答案
使用 转发声明避免循环依赖。
Avoid circular dependencies by using Forward Declarations.
class terminal;
class symbol
{
std::vector<terminal> first();
// ...
};
这种方法的推测是根据C ++标准未定义。
@Ben Voight指出:
There is a speculation of this approach being Undefined as per C++ standard.
@Ben Voight points out:
C ++ 03标准第17.6.4.8节说:
特别是,在以下情况下,效果未定义:...如果在实例化模板组件时将不完整的类型用作模板参数除非特别允许该组件...
"In particular, the effects are undefined in the following cases: ... if an incomplete type is used as a template argument when instantiating a template component, unless specifically allowed for that component...
是否 std :: vector< X> f 是
std :: vector< X>
正在讨论 这里 。如果答案证明是,那么这个答案没有好处,我会删除相同,否则这将保持有效。
Whether std::vector<X> f();
is std::vector<X>
an instantiation, is being discussed here. If the answer there proves it is then this answer holds no good and I will delete the same, or else this stays valid.
这篇关于C ++类方法,返回向量< subclass>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!