我如何使用这些类?(How do I work with these classes? [duplicate])

系统教程 行业动态 更新时间:2024-06-14 16:59:47
我如何使用这些类?(How do I work with these classes? [duplicate])

这个问题在这里已经有了答案:

在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 answers

I 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; }

更多推荐

本文发布于:2023-04-17 09:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/fdc58ba56a68abcd4db26caa8dffc463.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   work   duplicate   classes

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!