【问题标题】:How to define a member struct in a separate file for C++如何在 C++ 的单独文件中定义成员结构
【发布时间】:2019-10-22 16:01:46
【问题描述】:

我试图在一个单独的文件中定义一个类的成员结构。但是,我不确定实现它的正确方法是什么。

以下是我尝试过的。在 code1.cpp 是主要的源代码。我想将成员结构 Mid 的定义放到一个单独的文件 code2.cpp 中。但是,为了让 code2.cpp 知道该结构是 TestCls 的一部分,我在那里导入 code1.cpp 并添加了警卫。我知道这行不通,但我不知道如何使它工作。谢谢

code1.cpp:

#include <iostream>
#include "code2.cpp"


class TestCls {
 public:
  struct Mid;
};

int main() {
  TestCls::Mid mid1;
  std::cout << mid1.a << std::endl;
}

code2.cpp

#ifndef XXX
#define XXX


#include <iostream>
#include <sys/dtrace.h>
#include "code1.cpp"

struct TestCls::Mid {
  int a = 0;
};

#endif //XXX

【问题讨论】:

  • 无关的,一般来说你不应该包含 cpp 文件,只包含标题。你也有一个循环包含,因为只有文件有一个包含保护。
  • 您需要将声明放在 .h 中。

标签: c++ include


【解决方案1】:
  1. 不要包含 cpp 文件。只包含头文件。虽然头文件在技术上可以有任何(或没有)后缀,但使用源文件后缀可能最终会使构建系统或编译器混淆,以为它应该被编译,而您不想对头文件进行此操作。 .h 或 .hpp 和其他几个是常用的标题后缀。

  2. 您的 code2.cpp 包含 code1.cpp,而 code1.cpp 包含 code2.cpp。没有这样的递归包含。虽然包含保护可以防止无限递归,但在某些情况下这很容易中断。

对于像这样的小程序,作为练习,我建议你先将它完全写到一个文件中。例如,以下是正确的:

class TestCls {
 public:
  struct Mid;
};

struct TestCls::Mid {
  int a = 0;
};

#include <iostream>

int main() {
  TestCls::Mid mid1;
  std::cout << mid1.a << std::endl;
}

现在,您可以在保持顺序的同时将文件分割成多个文件。

// TestCls.hpp
#pragma once
class TestCls {
 public:
  struct Mid;
};

// TestClsMid.hpp
#pragma once
#include "TestCls.hpp"
struct TestCls::Mid {
  int a = 0;
};

// main.cpp
#include "TestCls.hpp"
#include "TestClsMid.hpp"

#include <iostream>

int main() {
  TestCls::Mid mid1;
  std::cout << mid1.a << std::endl;
}

为了简单起见,我使用了#pragma once,如果您愿意,可以选择购买宏守卫。

也就是说,我建议重新考虑在 TestCls.hpp 中不定义 TestCls::Mid 是否有任何优势。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多