这个问题在这里已经有了答案:
在C ++ 2答案中 声明公共静态变量时出现链接错误我是C ++新手,我尝试启动一个项目,每次创建一个ATM类的新实例时,它都会将accountID设置为1并显示当前帐户ID。 这是我的代码:
// Bank ATM.cpp : Defines the entry point for the console application. #include "stdafx.h" #include "ATM.h" int main() { ATM abunch[15]; for (int i = 0; i < 15; i++){ abunch[i] = ATM(); } return 0; } //ATM.h #include "stdafx.h" #ifndef atm #define atm class ATM { static int accountID; public: ATM(); }; int ATM::accountID = 0; #endif //ATM.cpp #include "stdafx.h" #include "ATM.h" #include <iostream> ATM::ATM() { ++accountID; std::cout << accountID; }我收到以下错误消息:
我究竟做错了什么?
This question already has an answer here:
Link error when declaring public static variables in C++ 2 answersI am new to C++ and I am trying to start a project where every time I create a new instance of the ATM class it incements accountID by 1 and displays the current account ID. This is my code:
// Bank ATM.cpp : Defines the entry point for the console application. #include "stdafx.h" #include "ATM.h" int main() { ATM abunch[15]; for (int i = 0; i < 15; i++){ abunch[i] = ATM(); } return 0; } //ATM.h #include "stdafx.h" #ifndef atm #define atm class ATM { static int accountID; public: ATM(); }; int ATM::accountID = 0; #endif //ATM.cpp #include "stdafx.h" #include "ATM.h" #include <iostream> ATM::ATM() { ++accountID; std::cout << accountID; }I get The following error message:
What am I doing wrong?
最满意答案
由于ATM::accountID是在.h文件中声明的,在类之外,每当该文件包含在另一个文件中时,它都会进行全局声明。 你包括两次; 在main.cpp和ATM.cpp 。 这是一个禁忌。
声明需要转移到ATM.cpp
//ATM.h #include "stdafx.h" #ifndef atm #define atm class ATM { static int accountID; public: ATM(); }; int ATM::accountID = 0; // <--- remove this line #endif //ATM.cpp #include "stdafx.h" #include "ATM.h" #include <iostream> int ATM::accountID = 0; // <----put it here ATM::ATM() { ++accountID; std::cout << accountID; }Because ATM::accountID is declared in a .h file, outside of a class, it is globally declared every time that file is included in another file. You include it twice; in main.cpp and in ATM.cpp. That's a no-no.
The declaration needs to move to ATM.cpp
//ATM.h #include "stdafx.h" #ifndef atm #define atm class ATM { static int accountID; public: ATM(); }; int ATM::accountID = 0; // <--- remove this line #endif //ATM.cpp #include "stdafx.h" #include "ATM.h" #include <iostream> int ATM::accountID = 0; // <----put it here ATM::ATM() { ++accountID; std::cout << accountID; }更多推荐
发布评论