声明一个带有构造函数参数的成员变量
// In A.h
class A
{
public:
enum eMyEnum{ eOne, eTwo, eThree };
public:
A(eMyEnum e);
}
// In B.h
#include "A.h"
class B
{
B();
private:
A memberA;
}
// In B.cpp
#include "B.h"
B::B(void) : memberA(A::eOne)
{}
使用 g++ 编译器时,“memberA”的声明给了我一个编译错误: 错误:'A::eOne' 不是一种类型
我该如何克服这个问题?我是否只需要创建一个不带参数的默认构造函数?
// In A.h
class A
{
public:
enum eMyEnum{ eOne, eTwo, eThree };
public:
A(eMyEnum e);
}
// In B.h
#include "A.h"
class B
{
B();
private:
A memberA;
}
// In B.cpp
#include "B.h"
B::B(void) : memberA(A::eOne)
{}
The declaration to 'memberA' gives me a compile error using the g++ compiler:
error: 'A::eOne' is not a type
How can I overcome this? Do I simply need to create a default constructor that takes no parameters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
听起来您正在尝试初始化成员变量。你可以这样做:
It sounds like you are trying to initialise a member variable. You could do something like:
A
构造函数需要一个eMyEnum
。目前尚不清楚为什么您希望 B 的构造函数也不接受 eMyEnum 参数。无论如何,假设您的目标是将参数作为A::eOne
传递给A
的构造函数(而不是A ::eMyEnum::eOne
),您可以尝试以下代码,它使用typedef
。但是,请注意
memberA
的构造函数始终以A::eOne
的参数进行调用。您尚未展示如何在构造函数中使用此参数,但我认为在您的实际代码中它初始化了A
的成员。如果该成员必须始终具有相同的值,请将其设置为 const 并从构造函数中删除该参数。A
constructor expects aeMyEnum
. It is not clear why you would wantB
's constructor to not accept aneMyEnum
parameter too. Anyway, assuming that your aim is to pass the argument toA
's constructor asA::eOne
(as opposed toA::eMyEnum::eOne
), you could try the following code, which usestypedef
.However, notice that
memberA
's constructor is always called with the argument asA::eOne
. You have not showed how this argument is used in the constructor, but I presume that in your real code it initialises a member ofA
. If the member must always have the same value, make itconst
and remove the parameter from the constructor.eOne 不是类型,eMyEnum 是类型。你本质上说的是“你必须将文字 2 传递到这个方法中” - 它没有任何意义。如果您不想将枚举传递给其中,则必须澄清您的用途。
eOne is not the type, eMyEnum is the type. What you're essentially saying is that "You must pass the literal 2 into this method" - it doesn't make any sense. If you don't mean to pass an enum into it, you'll have to clarify what you were going for.