首次用C++编写类代码遇LNK2001错误,请求技术支持
Hey there! Let's tackle your problem head-on—first that confusing linker error, then a quick tweak to your class code.
1. Resolving the LNK2001: unresolved external symbol "_WinMain@16" Error
This error has nothing to do with your code logic—it's a project configuration issue in Visual Studio:
- Your code uses
int main()(the standard entry point for console programs), but your project is set to build a Windows desktop application. Visual Studio's linker expectsWinMainas the entry point for Windows apps, hence the missing symbol error.
Here's how to fix it:
- Right-click your project in the Solution Explorer → Select Properties
- Go to Configuration Properties → Linker → System
- Find the Subsystem dropdown, change it from
Windows (/SUBSYSTEM:WINDOWS)toConsole (/SUBSYSTEM:CONSOLE) - Click Apply then OK, then rebuild your project.
2. Minor Code Improvement for Your myClass
Your code will work once the linker issue is fixed, but there's a small best practice to add: your private member name isn't initialized when an object is created. While your output() function assigns it a value, it's better to initialize members in a constructor to avoid accidental use of uninitialized values.
Update your header file like this:
#pragma once class myClass { public: // Add a constructor to initialize the member variable myClass() : name(0) {} int output(int exp) { name = exp; return name; } private: int name; protected: };
That's it! After adjusting the project setting and adding the constructor, your code should compile and run smoothly.
内容的提问来源于stack exchange,提问作者Jeroen

