如何在一个类中使用另一个类中的函数
How to use functions from one class in another?
我有三个类,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.cpp
、Y.cpp
和Z.cpp
,并将其与包含int main(/**/)
函数的编译单元一起链接到可执行文件中。
相关文章:
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 将 N-arg 函数包装到另一个函数中
- C++从另一个函数退出函数
- 视觉我希望一个函数在另一个函数C++中进行计算
- 在另一个函数 (c++) 中调用变量
- 如何在另一个函数中使用返回值作为参数?
- 如何包装一个函数以适应另一个函数的所需类型
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- 如何将 lambda 函数作为参数发送到另一个函数
- 将可变参数从一个函数传递到另一个函数
- 有没有办法在另一个函数中加入线程?(即超出其自身范围)
- 存储另一个函数返回的布尔数组时遇到问题
- 我正在尝试将表的地址传递给要在另一个函数中使用的指针,但得到不兼容的指针类型
- 如何在C++中提供模板化函数作为另一个函数的参数,默认值?
- 将作业传递给另一个函数,而不会延迟 arduino
- 编译器在C++中调用另一个函数时,在参数中查找已删除的构造函数
- 将参数从一个函数传递到另一个函数(没有模板) - C++
- 如何利用指针从一个函数到另一个函数?
- 使用另一个函数调用一个函数(都在类中)时出现问题.没有错误代码C++
- 在 c++ 中,如何将当前函数的所有参数传递给另一个函数?