如果我有类 A 和 B,我如何在 A 中创建对 B 的引用?我读到你需要使用指针或引用,但我找不到更多信息。这是我正在谈论的示例:
class B;
class A {
public:
B * b_pointer;
void setSelf(B * given_b_pointer) {
b_pointer = given_b_pointer;
};
void printBName() {
print (b_pointer.my_name);
};
};
class B {
public:
string my_name;
void setSelf(string my_given_name) {
my_name = my_given_name;
};
}
这给了我几个错误。我做错了什么,我该如何解决?
编辑:相关错误信息:
error: request for member 'my_name' in '((B*)this)->A::b_pointer', which is of non-class type 'B*'.
错误消息稍作编辑,用伪类名替换实际的类名。
最佳答案
[更新] 您需要转发声明类 B,并且在声明 B 之前不能在该类中使用任何成员,因此请移动 printBName
的声明到代码文件。
class B; //Forward declaration
class A {
public:
B * b_ref;
...
void printBName(); //Need to forward declare this as well
};
class B {
...
};
//Now define printBName
void A::printBName(){
print (b_ref->my_name);// use -> to dereference b_ref
}
关于c++ - 如何从其上方定义的类中访问该类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7986549/