gcc: weffc++ with Wextra and member initialization
Suppose I have a class like this:
class MyClass {
private:
vector<MyOtherClass> myMember;
public:
MyClass(const YetAnotherClass& myCollection);
}
MyClass::MyClass(const YetAnotherClass& myCollection) {
myMember = convert(myCollection);
}
Or, in other words, I have a class with a member that's some other data converted to be used afterwards.
Now, the weffc++
flag helps catch some stupid mistakes and makes the compiler a lot more helpful. At the same time, I like Wextra
because it forces me to fix my mistakes.
The problem is that the code doesn't compile ("MyClass::myMember should be initialized in the member initialization list") and I dunno how to get around it. I guess I could make the myMember
a pointer and set it to NULL but I'd rather not do that. I also can't find a way to disable the warning, though I'm not sure that would be a good idea either.
I'm using GCC 4开发者_开发问答.5.2, if it makes any difference.
So, how should I go about this?
You're not actually using a member initialization list in this instance.
To use the member initialization list in this case, your constructor implementation would look like this:
MyClass::MyClass(const YetAnotherClass &myCollection)
: myMember(convert(myCollection))
{
}
The member initialization list is a comma separated list of member variables after the colon. Multiple member initializations would look something like this:
class MyClass
{
public:
MyClass();
private:
SomeType someMember;
SomeOtherType someOtherMember;
AnotherType anotherMember;
};
MyClass::MyClass() :
someMember(a),
someOtherMember(b),
anotherMember(5)
{}
MyClass::MyClass(const YetAnotherClass& myCollection):
myMember(convert(myCollection))
{
}
Did you try:
MyClass::MyClass(const YetAnotherClass& myCollection)
: myMember(convert(myCollection))
{
}
精彩评论