![](/img/trans.png)
[英]Why is there no multiple definition error when you define a class in a header file?
[英]Why does Declaring in header file and defining in file gives multiple definition error?
我是C ++编程的新手。 我对JAVA有更好的了解。 因此,我使用hackerrank尝试学习C ++。 为了跟踪每个程序,我开始使用单独的实体为每个程序或质询使用头文件和程序文件 。 因此,我正在尝试进行hackerrank练习输入和输出( https://www.hackerrank.com/challenges/cpp-input-and-output )。 因此,我试图以这种方式实现我的程序。
InputAndOuput.h
#ifndef INPUTANDOUTPUT_H_
#define INPUTANDOUTPUT_H_
int arr[3];
int m;
int InputAndOutput();
#endif
InputAndOutput.cpp
#include "InputAndOutput.h"
#include<iostream>
#include<cmath>
#include<cstdio>
int InputAndOutput(){
int arr[3];
for(int i1 = 0; i1 < 3 ; i1++)
std::cin >> arr[i1];
for(int i = 0; i < 3 ; i++)
m = m + arr[i];
return m;
}
main.cpp
#include<iostream>
//#include<day1DataTypes>
#include<cmath>
#include<cstdio>
//#include "day1DataTypes.h"
#include "InputAndOutput.h"
int main()
{
int k = InputAndOutput(); \\the error persists even the whole block is commented
std::cout << k << std::endl ;
}
这给出了以下错误;
Description Resource Path Location Type
first defined here Hackerrank line 6 C/C++ Problem
first defined here Hackerrank line 8 C/C++ Problem
make: *** [Hackerrank] Error 1 Hackerrank C/C++ Problem
multiple definition of `arr' Main.cpp /Hackerrank line 9 C/C++ Problem
multiple definition of `m' Main.cpp /Hackerrank line 12 C/C++ Problem
请解释一下这个符号有什么问题。顺便说一句,我使用的是eclipse,它在编译时抛出错误。
为了首先解释最简单的问题,让我们看一下“ int arr [3];”。
对于该变量声明,它在InputAndOutput.h标头中声明和实现。
main.cpp和InputAndOutput.cpp都包含头文件,因此两次实现了该变量。
要声明该变量(可以在其他文件中使用该变量),可以使用:
InputAndOutput.h
extern int arr[3];
extern int m;
InputAndOutput.cpp
int arr[3];
int m;
这告诉编译器,有两个变量arr和m在.h文件中声明,但是使用extern关键字在外部文件中实现。
请注意,您在问题中发布的代码只是C ++文件中的C。
在C ++中,不建议使用全局变量来存储数据。
因此,如果要删除全局变量并使用c ++ stl容器,则将具有以下内容:
InputAndOutput.h
#include <array>
int32_t InputAndOutput(std::array<int32_t, 3>& arr, int32_t& m);
InputAndOutput.cpp
int32_t InputAndOutput(std::array<int32_t, 3>& arr, int32_t& m)
{
for(auto i1 = 0; i1 < 3 ; i1++)
std::cin >> arr[i1];
for(auto i = 0; i < 3 ; i++)
m = m + arr[i];
return m;
}
main.cpp
int main()
{
auto arr = std::array<int32_t, 3>{0,0,0};
auto m = 0;
const auto k = InputAndOutput(arr, m);
std::cout << k << std::endl ;
}
现在,这应该可以解决您的大部分问题,但是,由于您没有提示用户输入内容,因此我在原始代码中看不到如何从std :: cin获取输入信息……一个错误。
由于您正在学习C ++,因此您应该学习的是Modern C ++,而不是C ++ 98。
我建议您在https://github.com/isocpp/CppCoreGuidelines上阅读
并且,也请访问Herb Sutter的网站,关于Almost-Always-Auto, 网址为https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.