首页 > 解决方案 > 我对范围和在 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

任何和所有的意见将不胜感激。

提前致谢!

标签: c++

解决方案


推荐阅读