我意识到错误来自在自定义类中使用向量,但我一直在努力解决它们。当它是类对象的一部分时,如何调用向量方法?
这些是我得到的错误:
Word.cpp: In member function ‘void Word::addPosition(int)’:
Word.cpp:20: error: request for member ‘push_back’ in ‘((Word*)this)->Word::positions’, which is of non-class type ‘std::vector<int, std::allocator<int> >*’
Word.cpp: In member function ‘int Word::getPosition(int)’:
Word.cpp:26: error: request for member ‘size’ in ‘((Word*)this)->Word::positions’, which is of non-class type ‘std::vector<int, std::allocator<int> >*’
Word.cpp:27: error: request for member ‘size’ in ‘((Word*)this)->Word::positions’, which is of non-class type ‘std::vector<int, std::allocator<int> >*’
Word.cpp:29: error: cannot convert ‘std::vector<int, std::allocator<int> >’ to ‘int’ in return
标题
#pragma once
#include <string>
#include <vector>
class Word {
public:
Word();
~Word();
void setWord(std::string);
void addPosition(int);
std::string getWord();
int getPosition(int);
private:
std::string word;
std::vector<int> *positions;
};
执行
#include "Word.h"
#include <string>
#include <vector>
Word::Word() {
this->word = "";
this->positions = new std::vector<int>(5);
}
void Word::setWord(std::string s) {
this->word = s;
}
void Word::addPosition(int i) {
this->positions.push_back(i);
}
std::string Word::getWord() {
return this->word;
}
int Word::getPosition(int i) {
if (i < this->positions.size() && i > 0) {
for (int j = 0; j < this->positions.size(); i++) {
if (i == j) {
return positions[j];
}
}
}
return -1;
}
编辑:这是设置课程的更好方法吗?标题:
#pragma once
#include <string>
#include <vector>
class Word {
public:
Word();
~Word();
void setWord(std::string);
void addPosition(int);
std::string getWord();
int getPosition(int);
private:
std::string word;
std::vector<int> positions;
};
执行:
Word::Word(){
word = "";
}
void Word::setWord(std::string s){
this -> word = s;
}
void Word::addPosition(int i){
this -> positions.push_back(i);
}
std::string Word::getWord(){
return this -> word;
}
int Word::getPosition(int i){
if (i < this -> positions.size() && i > 0) {
for (int j = 0; j<this -> positions.size(); i++) {
if (i == j) {
return (this->positions)[j];
}
}
}
return -1;
}
但现在我收到了这个错误:
Undefined symbols for architecture x86_64:
"_main", referenced from:
start in crt1.10.6.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status