A类需要B类,B类需要A类及其所有成员

Class A needs class B that needs class A and all its members

本文关键字:成员      更新时间:2023-10-16

我肯定处于绝望的境地。。。使用C++,我定义了这两个类:

// Console.hpp
#ifndef CLASS_Console
#define CLASS_Console
#include <iostream>
#include "Window.hpp"
class Console
{
public:
    Window *Win;
    Console(Windows *Win); // Which then does "this->Win = Win;"
    void AppendText(std::string);
    // And some more dozens functions
};
#endif
// Window.hpp
#ifndef CLASS_Window
#define CLASS_Window
#include <iostream>
#include "Size.hpp"
class Window
{
private:
    Console *m_Console;
public:
    Window(); // Which then does "m_Console = new Console(this); m_Console->AppendText("YEAH");"
    Console *getConsole(); // For use by another classes
    Size getSize();
    // And some more Tens and Tens of functions
};
#endif

一开始,人们会说:"使用远期申报!"

但是,考虑到我需要访问这几十个函数中的一些(以一种方式和另一种方式),有什么方法可以避免使用正向声明吗?

感谢您(未来)的回答!

但是,考虑到我需要访问这几十个函数中的一些(以一种方式和另一种方式),有什么方法可以避免使用正向声明吗?

我不确定你是否理解远期申报的作用。您只需要在window.hpp中为Console提供一个正向声明,然后从window.cpp中包括console.hpp

不,没有办法避免(至少是)前向声明。

但考虑到我需要访问的几十个功能中的一些

为什么这很重要?表演你量过东西了吗?如果没有,你就不能谈论表现。

正常结构为:

  1. 声明第一个类:class Console;
  2. 定义第二类:class Window { Console *c; ...};
  3. 定义第一个类:class Console { Window *w; ... };
  4. 定义成员函数Console::Console() { ... } ...

第一个类声明足以让您编写另一个类的定义(没有成员函数的定义)。

然后,在两个类的定义之后,成员函数被声明,因此成员函数的代码可以根据需要使用另一个类的成员。

如果设计时只需要从"外部"访问其中一个类,则可以考虑在Window(或其他方式)中嵌套Console