头文件应该插入两次吗?

时间:2014-04-03 07:56:14

标签: c++ header-files

我有关于包含头文件的以下问题。我正在学习课程,并出现了以下问题:

有人告诉我,类的声明应该进入一个单独的头文件,例如

//TestClass.hpp

#include <string>

class TestClass{
private:
  void init(); 
public:
  double r;
  double a;
  std::string Type;
  TestClass(const std::string& stringType);
};

在各自的TestClass.cpp中我正确定义了一切:

// TestClass.cpp
//

#include "TestClass.hpp" 
#include <string>
#include <iostream>


void TestClass::init()
{ // Initialise all default values
  // Default values
  r = 0.08;
  a = 0.30;
  Type = "Hello";
}

TestClass::TestClass(const std::string& stringType)
{ // Create option type
  init();
  Type = stringType;
  if (Type == "hello")
    Type = "Hello";
}

如果我在头文件中包含指令<string>,我是否必须在TestClass.cpp文件中再次包含它?

2 个答案:

答案 0 :(得分:4)

不,您在头文件中声明的所有内容都将被拉入包含标头的任何文件中。顺便说一下,您应添加include guard / #pragma once

答案 1 :(得分:4)

不,你不是,但我还是会这样做,以使代码更清晰:你明确地说那么&#34;这段代码需要 {{1正常工作&#34;。如果您将来因某种原因决定不使用string,则代码会停止编译,您必须手动解决缺少的内容。

请记住,TestClass.hpp没有任何魔力,它只是打开您指定的文件,并用该文件的内容替换#include。因此,您需要将文件#include粘贴到TestClass.hpp,但之后您需要将文件TestClass.cpp粘贴到string。实际上,TestClass.hpp也会包含在string中。

这就产生了第二个问题:你的档案中没有包含警戒。如果您TestClass.cpp一个文件,#include是您的#include,您将收到编译错误。正确实现的C ++标头看起来更像是以下内容:

TestClass.hpp

这样可以确保,如果您的文件第二次被包含在内,则无法实际使用。

这也可以通过使用自动包含保护来实现:

#ifndef TESTCLASS_HPP
#define TESTCLASS_HPP

// Code

#endif

然而,这是非标准的,因此一些编制者可能拒绝承认它。

相关问题