【问题标题】:C++ passing class instance between filesC ++在文件之间传递类实例
【发布时间】:2015-04-12 14:51:16
【问题描述】:

如何从 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;

【问题讨论】:

  • 首先,剪切 myfile2.cpp 中的所有内容(#include 除外)并将其粘贴到 myfile2.h。这就是您获得完整类型的方式。如果你想拆分声明和定义,谷歌它。
  • 我同意,没有任何解释的否决票不是很有帮助。也就是说,您是在要求编译器编译“test.a=1”而不保证test 一个名为a的成员。

标签: c++ file class


【解决方案1】:

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

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);
}

【讨论】:

  • 既然main没有看到abc的定义,那它怎么知道a这个成员呢?
  • @sp2danny:当然,你是对的。我将其更改为不需要公共类定义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多