iostream 头文件是否仅包含声明?
Does iostream header file just contain declarations?
我正在学习 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。这样做可以吗?
Because , I suspect if iostream contains definitions, this can lead to
a linking error related to multiple defintions.
你是对的,包含全局名称定义的 header 不能包含在多个源文件中而不导致 link 错误。标准 header 不会那样做。
Does iostream header file just contain declarations?
没有。它还包含定义。例如,指定包含 <ios>
,其中定义了 class 模板,例如 std::basic_istream
.
Here also I am including iostream. Is it okay to do so?
Because , I suspect if iostream contains definitions, this can lead to a linking error related to multiple defintions.
<iostream>
以及所有其他标准 header 将受到 header 守卫或类似机制的保护,以确保内容仅被包含一次,尽管存在多个包含宏。此外,根据 one-definition-rule.
,它们不会包含任何不允许出现在多个翻译单元中的定义。
所以,是的:可以多次包含标准 headers。在一个翻译单元内以及来自多个单独的翻译单元。
我正在学习 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。这样做可以吗?
Because , I suspect if iostream contains definitions, this can lead to a linking error related to multiple defintions.
你是对的,包含全局名称定义的 header 不能包含在多个源文件中而不导致 link 错误。标准 header 不会那样做。
Does iostream header file just contain declarations?
没有。它还包含定义。例如,指定包含 <ios>
,其中定义了 class 模板,例如 std::basic_istream
.
Here also I am including iostream. Is it okay to do so? Because , I suspect if iostream contains definitions, this can lead to a linking error related to multiple defintions.
<iostream>
以及所有其他标准 header 将受到 header 守卫或类似机制的保护,以确保内容仅被包含一次,尽管存在多个包含宏。此外,根据 one-definition-rule.
所以,是的:可以多次包含标准 headers。在一个翻译单元内以及来自多个单独的翻译单元。