Passing a reference of a base class to another function
Here is the problem i am facing, does anyone have solution?
Class A: public class B
{
// I want to pass a reference of B to开发者_如何学C Function
}
void ClassC::Function(class& B)
{
//do stuff
}
The way you are declaring the class is wrong:
class A : public B // no more class keyword here
{
}; // note the semicolon
void ClassC::Function(const B &b) // this is how you declare a parameter of type B&
{
}
You simply need to pass the object of type A
to the Function
. It'll work.
It's good to declare the parameter as const
if you want to take derived types too.
To pass the this
instance, you'd simply call:
classCObject.Function(*this);
Are you just having trouble with the syntax? It should be
void ClassC::Function(B& b)
{
b.DoSomething();
}
to make b
a reference of type B
.
精彩评论