Declaring a member variable that takes a constructor parameter

亡梦爱人 提交于 2019-12-10 17:44:41

问题


 // 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!