gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 04:11:35 25 4
gpt4 key购买 nike

我正在尝试访问父类 (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关键字

关于c++ - 在 C++ 中访问姐妹对象的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20173729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com