[英]Forward “Pre-declaring” a Class in C++
I have a situaion in which I want to declare a class member function returning a type that depends on the class itself. 我有一个情境,我想声明一个类成员函数返回一个依赖于类本身的类型。 Let me give you an example: 让我给你举个例子:
class Substring {
private:
string the_substring_;
public:
// (...)
static SubstringTree getAllSubstring(string main_string, int min_size);
};
And SubstringTree is defined as follows: 而SubstringTree的定义如下:
typedef set<Substring, Substring::Comparator> SubstringTree;
My problem is that if I put the SubstringTree definition after the Substring definition, the static method says it doesn't know SubstringTree. 我的问题是如果我在Substring定义之后放置SubstringTree定义,静态方法说它不知道SubstringTree。 If I reverse the declarations, then the typedef says it doesn't know Substring. 如果我反转声明,那么typedef表示它不知道Substring。
How can I do it? 我该怎么做? Thanks in advance. 提前致谢。
As you've written it, the short answer is you can't. 正如你所写,简短的回答是你不能。
You do have a few close alternatives: 你有几个接近的选择:
1) Declare SubstringTree in Substring 1)在子串中声明SubstringTree
class Substring {
public:
class Comparator;
typedef set< Substring, Comparator> Tree;
private:
string the_substring_;
public:
// (...)
static Tree getAllSubstring(string main_string, int min_size);
};
typedef Substring::Tree SubstringTree;
2) Define the Comparator outside of Substring: 2)在子串外定义比较器:
class Substring;
class SubstringComparator;
typedef set< Substring, SubstringComparator> SubstringTree;
class Substring {
public:
private:
string the_substring_;
public:
// (...)
static SubstringTree getAllSubstring(string main_string, int min_size);
};
3) You can use a template to delay the lookup until you have more declarations: 3)您可以使用模板来延迟查找,直到您有更多声明:
template <typename String>
struct TreeHelper
{
typedef set< String, typename String::Comparator> Tree;
};
class Substring {
public:
class Comparator;
private:
string the_substring_;
public:
// (...)
static TreeHelper<Substring>::Tree getAllSubstring(string main_string
, int min_size);
};
typedef TreeHelper<Substring>::Tree SubstringTree;
You could define it inside the class: 你可以在类中定义它:
class Substring {
private:
string the_substring_;
public:
// (...)
typedef set<Substring, Substring::Comparator> SubstringTree;
static SubstringTree getAllSubstring(string main_string, int min_size);
};
You can predeclare a class with this: 你可以用这个预先声明一个类:
class Foo;
Keep in mind that before the class is actually defined, you can only declare pointers to it, not instances. 请记住,在实际定义类之前,您只能声明指向它的指针,而不是实例。
forward declaration 前瞻性声明
class Substring;
I don't know if that will work for non pointer uses of Substring though. 我不知道这是否适用于Substring的非指针使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.