Think of inline definitions in a class as just syntactic sugar for declaring the function, and then defining outside of the class. Manually doing that would transform the code to
class Test{
public:
Test();
void setHeight(int h);
void printHeight();
int width = 6;
protected:
int height;
};
Test::Test()
{
cout<<"Test variable created...
";
// accessing width variable in constructor
cout<<"Width is "<<width<<".
";
}
void Test::setHeight(int h)
{
height = h;
}
void Test::printHeight()
{
cout<<"Height is "<<height<<" meters.
";
}
And you can see from this transformation that the class member is now "before" the function definitions, so there is no reason why they can't know about the variable.
The technical term for this is call the complete-class context and the jist of it is that when you are in the body of a member function or the class member initialization list, the class is considered complete and can use anything defined in the class, no matter where in the class it is declared.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…