访问C++中姐妹对象的成员变量

Access a member variable of a sister object in C++

本文关键字:成员 变量 对象 姐妹 C++ 访问      更新时间:2023-10-16

我试图访问父类(TestClassOne.h)中的对象(TestClassThree.h)中的一个变量。每个类都在自己的文件中,当我试图导入文件以实例化类时,它会崩溃。我怀疑这是因为导入循环。我不认为我可以使用前向类声明,因为这会限制对变量的访问。如何从TestClassTwo访问TestClassThree内部的变量?

//--TestClassOne.h--
#include "TestClassTwo.h"
#include "TestClassThree.h"
class TestClassOne {
public:
    TestClassTwo *myVariable;
    TestClassThree *mySecondVariable;
    TestClassOne() {
        myVariable = new TestClassTwo(this);
        mySecondVariable = new TestClassThree();
    }
};
//--TestClassTwo.h--
#include "TestClassOne.h" //<-- ERROR
class TestClassTwo {
public:
    TestClassOne *parent;
    TestClassTwo(TestClassOne *_parent) : parent(_parent) {
    }
    void setValue() {
        parent->mySecondVariable->mySecondVariable->value = 10;
    }
};

您可以使用forward class declarationsfriend关键字

尝试添加一个所谓的include-guard(参见这个so问题)。在TestClassOne.h中,在文件的顶部和底部添加以下行:

#ifndef TESTCLASSONE_H
#define TESTCLASSONE_H
[...]
#endif

也将其添加到TestClassTwo.h中,但将预处理器宏的名称更改为TESTCLASSTWO_H。

herzube和patato都回答了你的问题:

1-使用#ifndef/#define宏避免"包含循环",就像herzube解释的一样

2-使用前向类声明告诉编译器一个类将在之后定义

// 1- avoid "include loops"
#ifndef TESTCLASSONE_H
#define TESTCLASSONE_H
// 2- Forward classes declarations
class TestClassTwo;
class TestClassThree; // assuming TestClassThree needs TestClassOne.h
class TestClassOne{
...
};
#endif