2011-10-22 109 views
0

一个长标题的位,所以我很抱歉。但目前我的代码确实存在一些问题。它应该是相当普遍的,代码中有很多事情,所以我不会发布它,但我确实有这个问题。那就是:创建一个新的对象并将该对象存储在一个新类的向量中,属性消失

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

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

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

我的数据在转换过程中丢失的任何原因?

编辑:我已经实现了一个=运算符重载和复制操作符。但sentencesNonP中的words仍为空。

EDIT2: Sentence.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

EDIT3:下面是我的拷贝构造函数:

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]); 
    } 
} 
+0

是什么'Sentence'的拷贝构造函数呢?它一定在路上失去了属性。 – Vlad

+0

这就是我的想法,但没有重载的'='运算符。我应该实施一个,看看它是否有效吗?没有真正认为它会需要一个,因为它只是被推到一个向量上。 – Brandon

+0

等一下,它是否是'='重载或其他操作符? – Brandon

回答

0
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; 
+0

'words'实际上是'wordNonP'中每个元素的指针矢量,所以这就是为什么我按照我的方式编写了我的拷贝构造函数。改变你的方式,它仍然不会工作。我非常感谢你的建议,并且我已经改变了一些代码。编辑:正如我所提到的,它仍然不会复制存储在矢量中的所有单词? – Brandon

相关问题