gpt4 book ai didi

c++ - 错误: request for member . ..是非类类型的

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:54:11 26 4
gpt4 key购买 nike

我意识到错误是由于在自定义类中使用 vector 而引起的,但是我一直在努力解决这些问题。当 vector 方法作为类对象的一部分时,如何调用它?

这些是我得到的错误:

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

header
#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;
}

编辑:这是建立类(class)的更好方法吗?
header :
    #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

最佳答案

positions是一个指针。您需要取消引用它才能到达基本 vector :
this->positions->size();
通常,您遇到的错误是由于取消引用失败引起的(因为T*不是类类型;它是指针,而指针是原始类型)。

关于c++ - 错误: request for member . ..是非类类型的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18806285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com