问题
// 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?
回答1:
It sounds like you are trying to initialise a member variable. You could do something like:
class B
{
public:
B() : memberA(A::eOne) {} // Initializer list in constructor
private:
A memberA;
};
回答2:
A
constructor expects a eMyEnum
. It is not clear why you would want B
's constructor to not accept an eMyEnum
parameter too. Anyway, assuming that your aim is to pass the argument to A
's constructor as A::eOne
(as opposed to A::eMyEnum::eOne
), you could try the following code, which uses typedef
.
#include <iostream>
using namespace std;
class A {
public:
typedef enum { eOne, eTwo, eThree } eMyEnum;
public:
A(eMyEnum e) {
cout << "A ctor" << endl;
}
};
class B {
public:
B() : memberA(A::eOne) {
cout << "B ctor" << endl;
}
private:
A memberA;
};
int main() {
B b;
}
// output
A ctor
B ctor
However, notice that memberA
's constructor is always called with the argument as A::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 of A
. If the member must always have the same value, make it const
and remove the parameter from the constructor.
回答3:
class B
{
public:
B(A::eMyEnum someValue = A::eOne) : memberA(someValue) {};
private:
A memberA;
}
回答4:
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.
来源:https://stackoverflow.com/questions/7395160/declaring-a-member-variable-that-takes-a-constructor-parameter