使用向量的未定义参考 [英] Undefined Reference Using Vectors

查看:62
本文介绍了使用向量的未定义参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到这个未定义的引用错误:



I am getting this undefined reference error:

/tmp/ccYnTr05.o: In function `TourManager::addCity(City)':
tsp.cpp:(.text._ZN11TourManager7addCityE4City[TourManager::addCity(City)]+0x1c): undefined reference to `TourManager::destinationCities'
/tmp/ccYnTr05.o: In function `TourManager::getCity(int)':
tsp.cpp:(.text._ZN11TourManager7getCityEi[TourManager::getCity(int)]+0x14): undefined reference to `TourManager::destinationCities'
/tmp/ccYnTr05.o: In function `TourManager::numberOfCities()':
tsp.cpp:(.text._ZN11TourManager14numberOfCitiesEv[TourManager::numberOfCities()]+0x5): undefined reference to `TourManager::destinationCities'
collect2: ld returned 1 exit status





这是代码:





Here is the code:

class TourManager
{
private:
    
    static vector<City> destinationCities;
    
public:
    
    static void addCity(City city)
    {
        destinationCities.push_back(city);
    }
    
    static City getCity(int index)
    {
        return (City)destinationCities.at(index);
    }
    
    static int numberOfCities()
    {
        return (int)destinationCities.size();
    }
};





我不知道这个错误意味着什么,我当然不知道如何解决它。任何帮助将不胜感激。



I don't know what this error means and I certainly don't know how to fix it. Any help will be appreciated.

推荐答案

您可能需要在类外部定义/实例化静态。由于他独立于实例(静态),他需要在类之外定义才能实际存在,否则他刚被声明(通常你需要在cpp文件中进行实例化,如果我没记错的话,你不是允许在头文件中执行此操作。



同样的问题:

http://stackoverflow.com/questions/272900/undefined-reference-to-static-class-member [ ^ ]
You probably need to define/instantiate your static outside of the class. Since he's independent of instance (static), he needs to be defined outside of the class to actually exist, otherwise he's just been declared (usually you need to do the instantiate inside of the cpp file, if I remember correctly, you're not allowed to do it in a header file).

Same problem as this:
http://stackoverflow.com/questions/272900/undefined-reference-to-static-class-member[^]


代码在vs2010中看起来很好并且编译。

看起来你缺少了向量。

你需要行:



Code looks fine and compiles in vs2010.
Looks like you are missing vector.
You need lines:

#include <vector>;

using namespace std;


您在哪里为destinationCities分配内存?



您需要将destinationCities初始化为新的向量< city>在向它添加数据之前,否则它与空指针相同。
Where do you allocate the memory for destinationCities?

You need to initialize destinationCities to a new vector<city> before you can add data to it, otherwise its the same as a null pointer.


这篇关于使用向量的未定义参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆