c++ - 我对范围和在 C++ 中声明变量有疑问
问题描述
在学习了大量的 Javascript 之后,我最近开始学习 c++。
我很确定我面临的问题与范围/头文件被#included 的次数有关,但我需要澄清一下。
如果您查看我所拥有的 - 您可以看到我在 input.hpp 中注释掉了“int input”,并且我在 getInput() 函数的范围内实际在 input.cpp 中声明了它。有人可以详细解释为什么我能够编译它在这里编写的方式,但是如果我切换声明“int input”的位置,它将无法编译?注意:我得到的错误是“'input'的多重定义”
另外,我知道这是一个很长的帖子,所以如果我需要在另一个帖子中问这个问题,请告诉我。由于我是 C++ 新手,我是否正确分离了我的文件?
这些是我的文件:
主文件
#include <iostream>
#include "add.hpp"
#include "input.hpp"
int x = getInput();
int y = getInput();
int main()
{
std::cout << add(x, y) << std::endl;
return 0;
}
添加.cpp
#include "add.hpp"
#include <iostream>
int addCalc (int x, int y)
{
return (x + y);
}
std::string add (int x, int y)
{
return (std::to_string (x) + " + " + std::to_string (y) + " = " + std::to_string (addCalc (x, y)));
}
添加.hpp
#ifndef add_hpp
#define add_hpp
#include <iostream>
int addCalc(int x, int y);
std::string add(int x, int y);
#endif
输入.cpp
#include "input.hpp"
#include <iostream>
int getInput()
{
int input;
std::cout << "Enter a number: " << std::endl;
std::cin >> input;
return input;
}
输入.hpp
#ifndef input_hpp
#define input_hpp
#include <iostream>
int getInput();
//int input;
#endif
任何和所有的意见将不胜感激。
提前致谢!
解决方案
推荐阅读
- maps - 从谷歌地图中提取经纬度
- excel - 从 excel 中的数据创建一个 word docx - 每行一个 doc
- node.js - 节点:使用 PUT 更新数据库不适用于 MongoDB
- reactjs - 无法将样式应用于 react-native-progress-steps
- shell - sed: -e 表达式 #1, char 15: 未终止的 `s' 命令
- mysql - 为python2.7安装MySQLdb返回错误
- javascript - ImageCapture 质量差
- java - 有没有办法覆盖 Eclipse 服务器概述中的运行时环境行为?
- javascript - 为什么动态创建的加载器不起作用?
- google-cloud-platform - 如何在可恢复上传中指定自定义元数据(通过 XML API)?