【问题标题】:Passing the parent class pointer to child将父类指针传递给子类
【发布时间】:2013-06-22 16:26:54
【问题描述】:

我有两个类声明如下,但我得到编译错误,这似乎是由于循环#include。有谁知道如何解决这个问题?

我的目的是让子类保留指向父类的指针,以便子类可以访问父类的方法和属性。

#ifndef PARENT_H
#define PARENT_H
#include "child.h"

class Parent
{
public:
    Child* mychild;
    Parent();
};

#endif // PARENT_H


#ifndef CHILD_H
#define CHILD_H
#include "parent.h"
class Child
{
public:
    Parent* myparent;
    Child();
};

#endif // CHILD_H

【问题讨论】:

    标签: qt class methods properties parent-child


    【解决方案1】:

    只要你只存储一个指向类的指针,你不需要在头部有完整的类定义,你可以使用前向类声明,像这样:

    #ifndef PARENT_H
    #define PARENT_H
    
    class Child;
    
    class Parent
    {
    public:
        Child* mychild;
        Parent();
    };
    
    #endif // PARENT_H
    
    
    #ifndef CHILD_H
    #define CHILD_H
    
    class Parent;
    
    class Child
    {
    public:
        Parent* myparent;
        Child();
    };
    
    #endif // CHILD_H
    

    然后您必须在 child.cpp 中包含 parent.h,在 parent.cpp 中包含 child.h。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 2012-10-28
      • 1970-01-01
      • 2016-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多