C ++如何从包含的类调用父类方法? [英] C++ how to call a parent class method from contained class?

查看:765
本文介绍了C ++如何从包含的类调用父类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个包含的对象调用父类方法,但没有运气与下面的代码。

I am trying to make a call to a Parent class method from a contained object, but have no luck with the following code. What is the standard way to do it?

我已经搜索过,这似乎适用于继承的对象,但不适用于包含的对象。是不是称它为父类甚至是正确的?

I have searched around and this seems to work for inherited objects, but not for contained objects. Is it right to call it a Parent class even? Or is it called an Owner class?

class Parent{
private:
  Child mychild;

public:
  void doSomething();
}

class Child{
public:
  void doOtherThing();
}

void Child::doOtherThing(){
  Parent::doSomething();
}


推荐答案

访问包含它的类,并且通常不知道它包含。您需要以某种方式传递引用或指向包含类的指针 - 例如:

A contained object has no special access to the class that contains it, and in general does not know that it is contained. You need to pass a reference or a pointer to the containing class somehow - for example:

class Child{
public:
  void doOtherThing( Parent & p );
};

void Child::doOtherThing( Parent & p ){
   p.doSomething();
}

这篇关于C ++如何从包含的类调用父类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆