繁体   English   中英

C ++类可以通过引用本身传递吗?

[英]C++ Can a class pass itself by reference?

尝试将父类对象传递给子类对象,以便子类对象可以控制父类对象的方法。

但是,这导致与标题相关的问题。 我已经尝试过声明一个类,但是似乎首先声明的任何类总是很难读取下面声明的类。

这两个错误都与Device的构造函数有关,它们试图调用dm的hello world方法,它们是:

Use of undefined type 'DeviceManager'
Left of '->HelloWorld' must point to class/struct/union/generic type

...

//main.cpp
#include "parent.h"

void main()
{
    cout << "Created DeviceManager\n";
    DeviceManager* deviceManager = 0;
    deviceManager = new DeviceManager;

    cout << "Giving  DeviceManager a device\n";
    deviceManager->p = new Device(deviceManager);

    cout << "Giving  Device a reference to DevicenManager\n";
    deviceManager->Share();
}

...

class DeviceManager;
class Device
{
public:
    Device(DeviceManager* manager)
    {
              dm = 0;
        this->dm = manager;
        this->dm->HelloWorld();
    }

    DeviceManager* dm;
};

//device manager
class DeviceManager
{
public:
    DeviceManager()
    {
        p = 0;
    }
    void HelloWorld()
    {
        //if this calls we know the child has control over the parent.
        cout << "Hello World";
    }

    Device* p;
};

是。

要使用类成员和函数声明来解决循环依赖关系,可以向前声明一个类:

class A;

class B {
        A *a;
};

class A {
        B *b;
};

要定义访问另一个类的成员的类成员函数,必须在定义另一个类之后定义该函数:

class B;

class A {
public:
        void f(B &arg);
};

class B {
public:
        void g(A &arg);
};

void A::f(B &arg) {
        arg.g(*this);
}

void B::g(A &arg) {
        arg.f(*this);
}

通常,在C++项目中,您甚至不会遇到此问题:您会将函数定义(即实现)放入.cpp文件中,而将类定义放入头文件中。 如果需要,可以将类转发声明放入其自己的头文件中,该头文件包含在所有需要它们的头文件中。

有关如何将以上代码拆分为多个文件的完整示例:

cpp文件

#include "a.h"

#include "b.h"

void A::f(B &arg) {
    arg.g(*this);
}

cpp文件

#include "b.h"

#include "a.h"

void B::g(A &arg) {
    arg.f(*this);
}

#ifndef _A_H_
#define _A_H_

#include "forward_declarations.h"

class A {
public:
    void f(B &arg);
};

#endif //_A_H_

h

#ifndef _B_H_
#define _B_H_

#include "forward_declarations.h"

class B {
public:
    void g(A &arg);
};

#endif //_B_H_

forward_declarations.h

#ifndef _FORWARD_DECLARATIONS_H_
#define _FORWARD_DECLARATIONS_H_

class A;
class B;

#endif //_FORWARD_DECLARATIONS_H_

作为一般的经验法则,如果您需要前向声明一个类,则可能设计有误,应考虑是否有更好的方法(但也有完全有效的用例需要类前向声明​​)。

如果您不理解我的#ifndef#ifndef #define#endif预处理程序行:这些是标头保护符, 与其他位置包含的所有文件一起使用,除非您确切地知道自己在做什么。 相信我。 您会后悔省略一个。

如果您的问题是循环依赖性,则如下所示:

// DeviceManager.h
#include "device.h"
class DeviceManager
{
    DeviceManager(Device& device) {}
};

// Device.h
#include "DeviceManager.h"
class Device
{
    Device(DeviceManager& manager) {}
};

您可以通过向前声明其中一个类并通过指针传递对象来解决问题。

// Device.h
//#include "DeviceManager.h"
class DeviceManager;
class Device
{
    Device(DeviceManager* manager) {}
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM