In the head开发者_JAVA技巧er, I'm defining bool isActive. In classes derived from this one, I would like to make isActive false by default. I tried doing this by adding
AbstractClass::isActive = false;
to the cpp file, but that causes the error "Expected constructor, destructor, or type conversion before '=' token."
Initialize it in the class' constructor:
class AbstractClass {
bool isActive;
AbstractClass() : isActive(false) {
}
// ...
};
That the class contains abstract methods doesn't stop it from having a constructor that is used to initialize its member variables.
AbstractClass::isActive = false;
refers to a (non-existent) static class member. If that existed, it would exist as a single shared instance for the entire class, and you would in fact initialize it as you did.
But you have an instance variable, which means that every instance of the class has its own copy. To initialize that, you'd do what sth say; initialize it in the class's ctor, either in the ctor body or better, as sth suggests, in the initializer list.
精彩评论