2017-08-09 80 views
0

首先,我是编程的初学者,所以不要指望我理解每个特定于代码的单词。如何组织包括包含在C++中的多个类中

第二我有时在摄取缓慢。

第三我认为我涵盖了C++的基础知识,但就是这样。我很高兴当然学到更多!

我的问题:

我编写一些代码,带班体验。我做了两个类,每个类都有一个不同的.h和.cpp文件。现在每个人都使用标题iostreamstring

我应该如何包含那些没有任何问题?是否#pragma曾经足够?

第二个问题是关于using namespace std: 我应该在哪里把它(我知道这是不是一个坏的使用,但只北京时间对于小PROGRAMM)

第一个标题:

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

预先感谢您的回复。

+1

您需要提供(最小)示例代码。你的解释是不清楚究竟是什么问题 – Drop

回答

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

    }; 

} 

主。CPP

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

int main() 
{ 

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

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

} 

可以有你需要在两个不同的类相同10+头的情况下,我认为,在一个头puting他们可以帮助你看到的代码更好。 是的,preprocesor定义也很好,不要忘记。 (:

+0

坏主意。该通用头文件在每个使用它的源文件中引入了依赖关系:该头文件中的任何更改都需要重新编译**每个使用它的源文件。每个源文件都应该包含** **需要的头文件。 –

1

没有问题,包括在两个类头两次iostream和字符串'。

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

因此它适用于你的类头'。

此外,也有使用#pragma指令缺点说这里:https://stackoverflow.com/a/1946730/8438363

我建议使用预处理器定义卫士:

#ifndef __MY_HEADER__ 
#define __MY_HEADER__ 


//... your code here 

#endif 

希望这有助于。

+0

是的,包括守卫,不是这个特殊的形式,包含两个连续的名字分数('__MY_HEADER__')和以下划线开头且以大写字母开头的名称被保留供实施使用。不要在你的代码中使用它们。 –

+0

你能否提供一个链接指向包含警卫形式的指导方针/规则? – Theforgotten

0

您将需要使用包括guards.They确保编译器包括每个“包括”头文件(#包括“XXX.h”)只有一次

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