创建一个新对象并将该对象存储在新类的向量中,属性消失

Creating a new object and storing that object in a new class' vector, attributes disappear

本文关键字:对象 新类 向量 消失 属性 存储 一个 新对象 创建      更新时间:2023-10-16

标题太长了,很抱歉。但我现在的代码确实有点问题。它应该很一般,代码中有很多内容,所以我不会全部发布,但我确实有一个问题。这是:

Sentence newSentence(currentSentence, this, sentenceCount);
this->sentencesNonP.push_back(newSentence);

现在,newSentence有一个名为words的属性,其类型为std::vector<Word *>Word也是项目中的另一个类。

当我调试和检查newSentence的属性时,它显示words填充有长度4,然而当我检查作为std::vector<Sentence>sentencesNonP时,words矢量长度是0。我正在检查sentencesNonP的第一个点,因为它是第一个被推入的值,所以这并不是说我看错了sentencesNonP向量的位置。

我的数据在转换过程中丢失的原因是什么?

EDIT:我已经实现了=运算符重载和复制运算符。然而,wordssentencesNonP中仍然是空的。

第2版:句子.h(不包括在内(

class Word;
class Document;
class Sentence {
public:
    //Take out Document * document
    Sentence();
    Sentence(std::string value, Document * document = NULL, int senNum = 0);
    Sentence(const Sentence& newSent);
    //Sentence(std::string value);
    ~Sentence(void);
    Sentence & operator=(const Sentence newSent);
    Document * getDocument(void);
    void setDocument(Document * document);
    //__declspec(property(get = getDocument, put = setDocument)) Document * document;
    std::string getSentence(void);
    void setSentence(std::string word);
    //__declspec(property(get = getSentence, put = setSentence)) std::string str;
    void setSentenceNumber(unsigned int i);
    Word * operator[] (unsigned int i);
    unsigned int wordCount(void);
    unsigned int charCount(void);
    unsigned int sentenceNumber(void);
    std::vector<Word *> getWordsVector(void);
private:
    std::string sentence;
    std::vector<Word *> words;
    std::vector<Word> wordNonP;
    Document * myd;
    unsigned int senNum;
};

忽略注释掉的declspec

编辑3:这是我的复制构造函数:

Sentence::Sentence(const Sentence& newSent) {
    this->sentence = newSent.sentence;
    this->myd = newSent.myd;
    this->senNum = newSent.senNum;
    for (int i = 0; i < newSent.wordNonP.size(); i++) {
        this->wordNonP.push_back(newSent.wordNonP[i]);
        this->words.push_back(newSent.words[i]);
    }
}
for (int i = 0; i < newSent.wordNonP.size(); i++) {
    this->wordNonP.push_back(newSent.wordNonP[i]);
    this->words.push_back(newSent.words[i]);
}

如果wordNonP为空,则根本不会复制任何words。写入任一:

for (int i = 0; i < newSent.wordNonP.size(); i++)
    this->wordNonP.push_back(newSent.wordNonP[i]);
for (int i = 0; i < newSent.words.size(); i++)
    this->words.push_back(newSent.words[i]);

或者更简单:

this->wordNonP = newSent.wordNonP;
this->words = newSent.words;