当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - Put vector inside of a vector

问题描述:

i've been trying to make a function that can store vectors inside a vector and im having problems. I have made it work for vectors of int, but now im trying to use objects to fill it up and im having problems.

this is my header file:

class Animal

{

public:

Animal();

~Animal();

Animal(int , int, std::string);

void setLength(int);

void setWeight(int);

void setLocation(std::string);

int getLength();

int getWeight();

std::string getLocation();

private:

int length_;

int weight_;

std::string location_;

};

this is my cpp file:

Animal::Animal(int length, int weight, std::string location) : length_(length), weight_(weight), location_(location)

{}

void Animal::setLength(int length){

length_ = length;

}

void Animal::setWeight(int weight){

weight_ = weight;

}

void Animal::setLocation(std::string location){

location_ = location;

}

int Animal::getLength(){

return length_;

}

int Animal::getWeight(){

return weight_;

}

std::string Animal::getLocation(){

return location_;

}

Animal::~Animal()

{

}

and here is my main:

int _tmain(int argc, _TCHAR* argv[])

{

Animal test;

int i = -1;

int d = -1;

std::vector<std::vector<Animal> >N;

std::vector<Animal>M;

std::vector<Animal>D;

while (i++ != 5)

{

M.push_back(test);

M[i].setLength(20);

M[i].setLocation("test");

M[i].setWeight(30);

}

N.push_back(M);

while (d++ != 5)

{

D.push_back(test);

D[i].setLength(111);

D[i].setLocation("test2");

D[i].setWeight(222);

}

N.push_back(D);

std::cout << N[0][4].getLength() << std::endl;

std::cout << N[1][4].getLength();

return 0;

}

When i try to build i get two errors:

error LNK2019: unresolved external symbol "public: __thiscall Animal::Animal(void)" ([email protected]@[email protected]) referenced in function _wmain

And

error LNK1120: 1 unresolved externals

Can anyone of you see what I have done wrong? And maybe some of you have a better solution to my problem.

网友答案:

The linker error will likely go away by placing curly braces next to your default constructor...

Animal() {}

In addition, I noticed a bug in your code. To fix it, change this...

while (d++ != 5)
{

    D.push_back(test);

    D[i].setLength(111);
    D[i].setLocation("test2");
    D[i].setWeight(222);
}

to this...

while (d++ != 5)
{

    D.push_back(test);

    D[d].setLength(111);
    D[d].setLocation("test2");
    D[d].setWeight(222);
}

and it will work fine.

分享给朋友:
您可能感兴趣的文章:
随机阅读: