在集合中使用嵌套类时出现不完整的类型错误 我正在研究一些java代码到C++中的翻译。当我尝试编写代码时,如:
.h:在集合中使用嵌套类时出现不完整的类型错误 我正在研究一些java代码到C++中的翻译。当我尝试编写代码时,如:,c++,nested-class,incomplete-type,C++,Nested Class,Incomplete Type,.h: 我有一个不完整的类型错误。我理解这是因为嵌套类在b_集合中使用之前是不完整的。但是最好的解决方法是什么呢?您可以在.h文件中描述整个B类 这里有一个有效的例子 #包括 甲级{ 私人: B类{ B():foo(1){} int foo; }; std::集b_集; }; 但是,如果要将定义和实例化分开,可以执行以下操作: A.h #include<set> class A { private: class B{ public: B();
我有一个不完整的类型错误。我理解这是因为嵌套类在
b_集合
中使用之前是不完整的。但是最好的解决方法是什么呢?您可以在.h
文件中描述整个B
类
这里有一个有效的例子
#包括
甲级{
私人:
B类{
B():foo(1){}
int foo;
};
std::集b_集;
};
但是,如果要将定义和实例化分开,可以执行以下操作:
A.h
#include<set>
class A {
private:
class B{
public:
B();
private:
int someMethod();
int foo;
};
std::set<B> b_set;
};
一般来说,嵌套类可能是一个严重的PITA,因为要从它们访问任何内容,您必须跳转到所有的环
关于嵌套类的另一个很好的参考:
嗯,我迟到了,我知道,但我想指出另一种可能性,如果你想完全隐藏B类的内部结构:
class A
{
private:
class B;
std::set<B*> b_set;
};
A类
{
私人:
乙级;;
std::集b_集;
};
注意在集合中使用指针。然而,还有一个重要的区别:由于只插入了指针,所以仍然可以插入指向具有相同内容的不同实例的指针。要解决此问题,您需要一个自定义比较器:
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const
{
return *x < *y;
}
};
std::set<B*, Less> b_set;
};
A类
{
私人:
乙级;;
无结构
{
布尔运算符()(B常量*x,B常量*y)常量
{
返回*x<*y;
}
};
std::集b_集;
};
请注意(在前面的回答中没有提到这一点,但在这里也是必需的!)必须为B定义一个比较器(B或引用,而不是指针!):
A.h
#包括
甲级
{
私人:
乙级;;
无结构
{
布尔运算符()(B常量*x,B常量*y)常量;
};
std::集b_集;
};
A.cpp
A类::B类
{
friend bool Less::operator()(B常量*x,B常量*y)常量;
bool operatorhanks Andy!但在这种情况下,实现在“.h”文件中。这是一种好的做法吗?@xieziban:请看我的编辑。使用嵌套类需要一个非常好的参数,所以总括语句可能根本没有。你的回答对我很有帮助。thnx
#include "A.h"
A::B::B():foo(1){}
int A::B::someMethod(){
return 42;
}
class A
{
private:
class B;
std::set<B*> b_set;
};
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const
{
return *x < *y;
}
};
std::set<B*, Less> b_set;
};
#include <set>
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const;
};
std::set<B*, Less> b_set;
};
class A::B
{
friend bool Less::operator() (B const* x, B const* y) const;
bool operator<(B const& other) const
{
return foo < other.foo;
}
int foo;
};
bool A::Less::operator() (B const* x, B const* y) const
{
return *x < *y;
}
#include <set>
#include <memory>
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const;
};
std::set<std::unique_ptr<B>, Less> b_set;
};