开发者

Passing a reference of a base class to another function

开发者 https://www.devze.com 2022-12-14 01:13 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消