static constant referencing to parent variable
Lets say you want to use the same memory that a parent class does but would like a more fitting name for its new function. This is achieved like this (for example SOCKADDR from winsock):
class Parent{
int a;
};
#define myA a;
class Child: public Parent{
void开发者_运维技巧 print(){
cout<<myA;
}
};
Much like static const instead of a define - is there a C++ specific alternative of creating this reference?
One possibility would be:
class Child: public Parent
{
int& myA() { return a; }
void print()
{
cout << myA();
}
void DoSomethingElse()
{
myA() = 10;
}
};
Define a reference like this, and initialize it in the initializer-list!
class Child: public Parent
{
int& myA;
Child() : myA(Parent::a) //<-- note this!
{
}
void print()
{
cout<<myA; //myA is just an alias of a!
}
};
精彩评论