如何在一个类中使用另一个类中的函数

How to use functions from one class in another?

本文关键字:另一个 函数 一个      更新时间:2023-10-16

我有三个类,A、B 和 C.类 C 包括 A 和 B 类型的对象。在 C 的 .cpp 文件中,当我尝试在类型 A 和 B 的对象上使用 A 或 B 方法(在本例中为我编写的"打印"方法)时,我得到"方法'printA'未解析"。我在C.cpp中包括了A.h,B.h,A.cpp和B.cpp,并在C.h中写了"A类"和"B类"。如何让我的 C.cpp 文件访问 A 和 B 的方法?

以下是到目前为止我对 C.cpp 文件的内容:

    #include "C.h"
    #include "A.h"
    #include "A.cpp"
    #include "B.h"
    #include "B.cpp"
    using namespace std;
    void C::printC(){
        a.printA();
        b.printB();
    }

其中"a"和"b"在 C.h 文件中定义为类型 A 和 B 的对象。

.h文件中,您包含类的声明,而.cpp文件应包含定义。

您需要直接或通过间接寻址包含每个使用的声明,但没有定义(如果不是内联或模板)。

X.h

#ifndef X_HEADER
#define X_HEADER
struct X
{
  void printX();
};
#endif

是的

#ifndef Y_HEADER
#define Y_HEADER
struct Y
{
  void printY();
};
#endif

Z.h

#ifndef Z_HEADER
#define Z_HEADER
#include "X.h"
#include "Y.h"
struct Z
{
  X x;
  Y y;
  void printZ();
};
#endif

十.cpp

#include <iostream>
#include "X.h" // *
void X::printX () { std::cout << "X"; }

Y.cpp

#include <iostream>
#include "Y.h" // **
void Y::printY() { std::cout << "Y"; }

Z.cpp

#include "Z.h" // also includes X.h and Y.h due to * and **
// no need to include X.h and Y.h seperately here
// also no need to include any cpp file
void Z::printZ()
{ 
  x.printX(); 
  y.printY(); 
}

然后你需要分别编译X.cppY.cppZ.cpp,并将其与包含int main(/**/)函数的编译单元一起链接到可执行文件中。