【发布时间】:2014-03-08 14:07:15
【问题描述】:
我正在使用 Visual Studio 2012 创建一个 Windows 窗体应用程序。我遇到的问题是,当我编写程序的主要部分并且只有一种形式时,我希望 2 个向量在该形式中是全局的。但是现在大部分编程已经完成,我想专注于系统流程,因此引入了第二个表单作为主屏幕,用户将在其中按下按钮并进入我一直在处理的表单到现在。问题是我定义如下的向量:
namespace Project1 {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
vector<vector<Hexagon>>Grid; // 2d vector to hold grid of hexagon
vector<Hexagon>Selected; // 1d vector to hold selected hexagons
/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form{
....
编译程序时出现以下错误:
1) 错误 47 错误 LNK2005: "class std::vector >,class std::allocator > > > Project1::Grid" (?Grid@Project1@@3V?$vector@V?$vector@VHexagon@ @V?$allocator@VHexagon@@@std@@@std@@V?$allocator@V?$vector@VHexagon@@V?$allocator@VHexagon@@@std@@@std@@@2@@ std@@A) 已在 MainScreen.obj C:\Users\Ed\Documents\Visual Studio 2012\Projects\Project1\Project1\Myform.obj 中定义
2) 错误 48 错误 LNK2005: "class std::vector > Project1::Selected" (?Selected@Project1@@3V?$vector@VHexagon@@V?$allocator@VHexagon@@@std@@@ std@@A) 已在 MainScreen.obj C:\Users\Ed\Documents\Visual Studio 2012\Projects\Project1\Project1\Myform.obj 中定义
只是为了澄清 MainScreen 是我添加的表单,它首先被调用。
MyForm 是通过在 MainScreen 中按按钮访问的表单
我希望我已经提供了足够的信息。我认为这可能与在 MyForm.h 中的 project1 中声明两个向量有关,如上所示,我会将它们设为 MyForm 类的本地,但我不能,因为它是一个托管类。 谢谢
【问题讨论】:
-
你懂 C++ 吗?您在 h 文件中定义了全局变量。现在,如果您将此类 h 文件包含到多个 .cpp 文件中,则会出现链接器错误/
-
解决方法是:在h文件中将两个变量都定义为extern,并在一个.cpp文件中创建。
-
糟了!!当然!谢谢你应该早点意识到这一点
-
有趣的是,如果我将 namespace{} 放在向量定义周围,它现在可以工作,这是不好的做法吗?
-
h 和 cpp 文件应该匹配。如果您决定将这些变量放在 h 文件的命名空间中,请在 cpp 文件中执行此操作。
标签: c++ visual-c++ vector c++-cli linker-errors