我正在学习C ++编程。我正在编写一个程序来实现计算器功能:
可以看出,我包括了iostream头文件。
#include <iostream>
#include "calculator.h"
int main()
{
//This program is meant to mimic the functionality of a calculator which
//support basic arithmetic operations.
//we will ask the user to input the desired operation and operands
getUserInput();
//We perform the mathematical operation and return the result
computeResult();
//We will print the output to the screen
printResult();
return 0;
}
现在我正在为getUserInput函数编写一个单独的cpp文件。
#include<iostream>
int getUserInput()
{
int a;
std::cout << "enter your input " << std::endl;
std::cin >> a;
return (a);
}
这里我也包括iostream。可以吗?
因为,我怀疑iostream是否包含定义,这可能导致 与多个定义相关的链接错误。
答案 0 :(得分:3)
您是对的,一个包含全局名称定义的标头不能包含在多个源文件中,而不会引起链接错误。标准标头不这样做。
答案 1 :(得分:0)
iostream头文件仅包含声明吗?
不。它还包含定义。例如,指定包含<ios>
,其中std::basic_istream
定义类模板,例如<iostream>
。
这里我也包括iostream。可以吗? 因为,我怀疑iostream是否包含定义,所以这可能导致与多个定义相关的链接错误。
{{1}}以及所有其他标准标头都将受到标头保护程序或类似机制的保护,以确保即使有多个包含宏,内容也只能被包含一次。此外,根据“单定义规则”,它们将不包含不允许出现在多个翻译单元中的任何定义。
所以,是的:可以多次包含标准标头。既可以在一个翻译单元内,也可以在多个单独的翻译单元中。