程序编译asis。以及指出的段错误。
/*
* Testing of Vectors.
* Uses c++11 standard.
* gcc version 4.7.2
* compile with : g++ -std=c++11 -o vec vec.c++
*/
#include <iostream>
#include <string>
#include <vector>
#include <stdio.h>
#include <unistd.h>
using namespace std;
这个类工作正常。
/* declare Person class. */
class Name {
std::string first;
std::string last;
public:
Name(void);
Name(std::string first, std::string last){
this->first = first;
this->last = last;
}
~Name();
std::string GetFirstName(){
return this->first;
}
std::string GetLastName(){
return this->last;
}
};
这个类是我遇到问题的地方。
/* declare NamesVector class. */
class NamesVector {
std::vector<Name *> person_list;
public:
NamesVector(void);
~NamesVector(void);
virtual Name *getPerson(void);
virtual void addPerson(Name *);
virtual void Print(void);
virtual void FindPerson(std::string);
};
/* adds person to vector/list */
void NamesVector::addPerson(Name *n){
person_list.insert(person_list.begin(), n);
};
/* prints all persons */
void NamesVector::Print(){
for (auto v: person_list){
std::cout << v->GetFirstName() <<
" " << v->GetLastName() << std::endl;
}
};
/* main() */
int main(int argc, char **argv){
我已经尝试过:NamesVector *nv = new NamesVector() 这里它给出的只是 错误:'未定义对 `NamesVector::NamesVector()' 的引用 编译。
除此之外,我还尝试替换:
NamesVector *peopleList;带有 NamesVector peopleList;
(并在需要时对代码进行了适当的更改。)
编译时出现如下错误:
对 `NamesVector::NamesVector()' 的 undefined reference
对 `NamesVector::~NamesVector() 的 undefined reference
/* pointer to person list */
NamesVector *peopleList;
/* pointer to a person */
Name *person;
/* instanseate new person */
person = new Name("Joseph", "Heller");
/* works ok */
std::cout << person->GetFirstName() << " "
<< person->GetLastName() << std::endl;
这是程序段错误的地方。有任何想法吗?
/* segfaults - Why!?! - insert into peopleList vector */
peopleList->addPerson(person);
peopleList->Print();
std::cout << std::endl << std::endl;
return EXIT_SUCCESS;
}
最佳答案
您必须为类 NamesVector 定义一个构造函数和一个析构函数:
// constructor
NamesVector::NamesVector() {
// create an instance of the vector
person_list = new Vector<Name *>();
}
// destructor
NamesVector::~NamesVector() {
// delete the instance of the vector
delete person_list;
}
当你定义构造函数和析构函数时,你应该能够调用:
NamesVector *nv= new NamesVector().
关于类中的 C++ vector - 程序段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19614446/