访问C++中姐妹对象的成员变量
Access a member variable of a sister object in C++
我试图访问父类(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 declarations
和friend
关键字
尝试添加一个所谓的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
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 内置函数可查看CPP中的成员变量
- 是否可以初始化不可复制类型的成员变量(或基类)
- 将包含C样式数组的对象初始化为成员变量(C++)
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- 在循环中按顺序遍历成员变量
- c++类声明时,相同的例程,不同的成员变量类型
- 如何从另一个文件继承私有成员变量和公共函数
- 在C++类中,是否必须初始化作为数组的成员变量
- 如何从子成员函数修改父公共成员变量
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 从私有成员变量的成员方法返回unique_ptr
- 在派生类中使用基类的私有成员变量的最佳方法
- 静态 constexpr 类成员变量对多线程读取是否安全?
- C++:是否可以使用非静态成员变量模板?
- 打印所有继承的类成员变量和方法
- 如何在复杂继承中访问静态成员变量
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 成员变量与函数概念检查