【问题标题】:Having a class creator and a class child how can a child call creator function not having a ptr to actual creator?拥有一个班级创建者和一个班级孩子,一个孩子如何调用没有实际创建者的ptr的创建者函数?
【发布时间】:2011-10-05 16:51:45
【问题描述】:

所以我有一个class_instantiator,它在自己内部创建了一个my_class a 的实例。 a 是否可以调用任何 class_instantiator 方法,没有指向 class_instantiator 的指针,只有其接口可用,任何 Boost 库都可以吗?

伪代码示例:

struct my_class 
{
  void call()
  {
    try{
    call_parent_function(instansiator_function);
    }catch (exception &e)
    }
};

struct class_instantiator
{
  void instansiator_function(){ cout << "Hello!";};
  void fun()
  {
   my_class a;
   a.call();
  }
};

【问题讨论】:

  • 你从哪里得到任何东西?这看起来像两个独立的结构。
  • 这里没有parent的概念。您只是从另一个结构/类中实例化另一个结构/类。
  • 如果您清楚地解释了您实际上想要实现的目标,也许会有所帮助。也许我们可以提出一个解决方案。截至目前(即使使用您的伪代码),这一切都没有多大意义。但这可能只是我。
  • 拥有void main() 作为班级成员看起来像某种其他语言。您是否尝试用 C++ 编写非 C++ 代码?

标签: c++ oop boost


【解决方案1】:
[edan@edan tmp]$ g++ parent.cpp
[edan@edan tmp]$ ./a.out 
parent_method!
[edan@edan tmp]$ cat parent.cpp 
#include <boost/shared_ptr.hpp>
#include <iostream>


class my_parent {
    protected:
        void parent_method() { std::cout << "parent_method!" << std::endl; }
};

class my_calss : public my_parent {
    public:
        void call_my_parent() { my_parent::parent_method(); }
};

int
main() {
    boost::shared_ptr<my_calss> my_ojb( new my_calss );
    my_ojb->call_my_parent();
    return 1;
}

【讨论】:

    【解决方案2】:

    如果您尝试进行循环引用(听起来是这样的?)我会说您可能做错了什么。你能给我们一个具体的例子来说明你想要实现的目标吗?

    只要不是私有的,子类就应该能够调用它的父方法。

    【讨论】:

      【解决方案3】:

      不是 100% 清楚你在问什么,但要调用一个类的成员函数,你需要一个该类的实际实例(对象)。但是,如果您的函数(在您的示例中为 Me::pf())不需要访问您的类非静态成员数据,那么您可以将您的函数声明为静态并直接调用它。我已经相应地修改了你的例子。另外,请注意,您在编写方式时有循环引用(您好需要查看 Me 的定义,反之亦然),所以我稍微重新组织了它。

      struct Hello 
      {
          void call_static_member();
      };
      
      
      struct Me
      {
          static void pf(){ std::cout << "Hello!";}
          void main()
          {
              Hello a;
          }
      };
      
      void Hello::call_static_member()
      {
      try{
          Me::pf();
      }catch (exception &e){}
      }  
      

      【讨论】:

        猜你喜欢
        • 2020-03-15
        • 1970-01-01
        • 2022-01-21
        • 2013-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        相关资源
        最近更新 更多