gpt4 book ai didi

c++ - 在类(class)之间共享信息

转载 作者:行者123 更新时间:2023-11-30 02:01:27 24 4
gpt4 key购买 nike

我正在尝试使用来自 here 的信息在类(class)之间共享信息,除了我无法编译这两个类,因此相互沟通。

所以,我想要的是让 ClassB 获得对 ClassA 的引用,并且ClassBClassA 中初始化。

编译器错误(使用 g++):

In member function 'void ClassA::foo()':
hello.cpp:9: error: 'ClassB' was not declared in this scope
hello.cpp:9: error: 'someB' was not declared in this scope
hello.cpp:9: error: expected type-specifier before 'ClassB'
hello.cpp:9: error: expected ';' before 'ClassB'

然后我尝试在 ClassA 之前添加 class ClassB;

喜欢:

class ClassB; // just this here.

class ClassA; // all of classA here.

class ClassB; // all of classB here.

然后我得到:

hello.cpp: In member function 'void ClassA::foo()':
hello.cpp:11: error: invalid use of incomplete type 'struct ClassB'
hello.cpp:3: error: forward declaration of 'struct ClassB'
hello.cpp:12: error: invalid use of incomplete type 'struct ClassB'
hello.cpp:3: error: forward declaration of 'struct ClassB'


这是我基于上述网站尝试使用的代码:

include stdio.h

class ClassA {
public:
void foo() {
ClassB *someB = new ClassB();
someB->setRelative(this);
}

void bar() {
printf("B is communicating with me =)\n");
}
};

class ClassB {

ClassA *m_relative;

public:
void setRelative(ClassA *other) {
this->m_relative = other;
}

void foo() {
m_relative->bar();
}
};

最佳答案

你显然在这里有一个循环依赖,你不能只使用标题来真正解决这个问题(可能有一些宏技巧,但我不会担心)。

您应该做的是将您的代码拆分为声明( header )和实现。

啊啊

// only include this file once per translation unit
#pragma once

// tell the compiler B is going to be a class,
// so B* is a pointer to a class - nothing more is needed for now.
class B;

// full declaration of A
class A {
B *child;

public:
A(void);
}

a.cpp

#include "a.h" // included whenever the structure/size of A has to be known
#include "b.h" // same for B

A::A(void) : child(new B(this)) {
// do something with child or...
B * = new B(this);
}

b.h

// only include this file once per translation unit
#pragma once

// again, just tell the compiler A is going to be a class
class A;

class B {
A *parent;
public:
B(A *pparent);
}

b.cpp

#include "a.h"
#include "b.h"

B::B(A *pparent) : parent(pparent) {
// do something with parent
}

关于c++ - 在类(class)之间共享信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14083733/

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