gpt4 book ai didi

C++ 在文件之间传递类实例

转载 作者:行者123 更新时间:2023-11-28 06:19:16 26 4
gpt4 key购买 nike

如何从 main 访问 test.a?
这是我的代码:

myfile1.cpp:

#include "myfile2.h"
int main()
{
test.a=1; //this gives error "incomplete type is not allowed"
}

myfile2.h:

class abc;
abc test;

myfile2.cpp:

#include "myfile2.h"

class abc{
public:
int a;
abc():
a(0){}
} test;

最佳答案

您不能定义一个不完整类型的变量,但您可以声明一个。如果你不想公开类定义,那么你不能访问你定义类的翻译单元之外的类成员,所以你还需要提供访问器。这是一种可能的方法:

header.h:

class abc;                       // declares the name "abc"

extern abc test; // declares the name "test"

void set_a(abc & obj, int val); // declares the name "set_a"

impl.cpp:

#include "header.h"

class abc { /* definition */ };

abc test;

void set_a(abc & obj, int val) { obj.a = val; }

ma​​in.cpp:

#include "header.h"

int main()
{
set_a(test, 1);
}

关于C++ 在文件之间传递类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29590766/

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