如何组织包括C ++中的多个类

时间:2017-08-09 08:57:48

标签: c++ class header include

首先,我是编程的初学者,所以不要指望我理解每个特定于代码的单词。

第二,我有时会慢慢接受。

第三,我认为我已经介绍了C ++的基础知识,但就是这样。我很高兴当然能学到更多东西!

致我的问题:

我正在编写一些代码来体验类。我创建了两个类,每个类都在一个不同的.h和.cpp文件中。现在每个人都使用标题iostreamstring

如何在不出现任何问题的情况下包含这些内容? #pragma一次就够了吗?

第二个问题是using namespace std: 我应该把它放在哪里(我知道这不是一个坏用途,但只适用于小型程序)

第一个标题:

#pragma once

#include <iostream>
#include <string>  

//using namespace std Nr.1

class one
{

};

第二个标题:

#pragma once

#include <iostream>
#include <string>  

//using namespace std Nr.2

class two
{

};

最后主要:

#include "one.h"
#include "two.h"

//using namespace std Nr.3

int main()
{
   return 1;
};

提前感谢您的回复。

3 个答案:

答案 0 :(得分:1)

没有任何问题,包括两个类标题中的两次iostream和字符串&#39;。

#pragma指令用于保护您自己类型的两个类型(typedef,classes)声明。

因此它适用于您的班级标题&#39;。

此外,使用#pragma指令存在缺点:https://stackoverflow.com/a/1946730/8438363

我建议使用预处理器定义防护:

#ifndef __MY_HEADER__
#define __MY_HEADER__


//... your code here

#endif

希望这有帮助。

答案 1 :(得分:0)

您将需要使用Include警卫。它们确保编译器包含每个&#34;包含&#34;头文件(#include&#34; XXX.h&#34;)只有一次。

但是如果你要创建一个小应用程序&amp;如果需要,不要介意重新编译/重建整个项目,然后将公共头文件放在专用的头文件中是公平的游戏&amp;保持代码清洁&amp;小。

答案 2 :(得分:-1)

您还可以使用所需的所有常见依赖项生成标题,并将其包含在需要这些依赖项的每个类中。这是一个简单的例子:

Core.h

#include <iostream>
#include <string>
// include most common headers

using namespace std;

One.h

#pragma once
#include "Core.h"
// if you need a header only for this class, put it here
// if you need a header in mutiple classes, put in Core.h

namespace one {

    class One
    {
    public:

        One();
       ~One();

        void sumFromFirstNamespace(string firsNumber, string secondNumber)
        {
          //convert string to int
          int first = stoi(firsNumber);
          int second = stoi(secondNumber);

          int result = first + second;

          cout << result << endl;
        }
    };

}

Two.h

#pragma once
#include "Core.h"
// if you need a header only for this class, put it here
// if you need a header in mutiple classes, put in Core.h

namespace two{
    class Two
    {
    public:
        Two();
       ~Two();

        void sumFromSecondtNamespace(string firsNumber, string secondNumber)
        {
          //convert string to int
          int first = stoi(firsNumber);
          int second = stoi(secondNumber);

          int result = first + second;

          cout << result << endl;
       }

    };

}

的main.cpp

#include "One.h"
#include "Two.h"

int main()
{

     one::One firstClass;
     two::Two secondClass;

     firstClass.sumFromFirstNamespace("10", "20");
     secondClass.sumFromSecondtNamespace("20", "30");

}

在某些情况下,您需要在两个不同的类中使用相同的10+标题,我认为将它们放在一个标题中可以帮助您更好地查看代码。 是的,预处理器定义也很好,不要忘记。 (: