c++返回元素在没有代码的行上给出访问冲突



当我试图从数组中返回一个元素时,我的程序崩溃,并在visualstudio2012中显示访问违规。我不知道这怎么可能,因为我初始化了数组并为它分配了内存。我有一个类Tweet,用于初始化Tweet。我还有一个类索引元素,它将具有相同标签的tweet放在一个数组中。索引元素的标题:

#ifndef INDEXELEMENT_H
#define INDEXELEMENT_H
#include "Tweet.h"
#include <string>
class IndexElement {
private:
    std::string hashtag;
    int size;
    Tweet* array;
    int memory;
public:
    IndexElement(std::string tag);
    IndexElement(const IndexElement& copy);
// Default constructor om makkelijker te kunnen werken in de klasse HashTagIndexer.
    IndexElement();
    ~IndexElement();
public:
    std::string getHashTag() const;
    void addTweet(Tweet tweet);
    int getNumTweets() const;
    Tweet getTweet(int i) const;
};
#endif

推特标题:

#ifndef TWEET_H
#define TWEET_H
#include <string>
class Tweet{
private:
    int id;
    std::string tweeter;
    time_t date;
    std::string tweet;
    std::string* tags;
    int num_tags;
public:
    Tweet(int id, std::string tweeter, time_t date, std::string tweet, std::string* tags, int     num_tags);
    Tweet();
    ~Tweet();
public:
    int getID() const;
    std::string getTweeter() const;
    time_t getDate() const;
    std::string getTweet() const;
    int getNumHashtags() const;
    std::string getHashtag(int i) const;
};
#endif

我做了一些测试,但它在这次测试中给了我一个错误:

bool addTweetIndexElementTest()
{
    IndexElement a("#test");
    string tags[1] = {"#test"};
    Tweet t1(1,"lennart",0,"dit is een teststring",tags,1);
    a.addTweet(t1);
    cout << a.getTweet(0).getID(); // program crashes here!!
}

getTweet实现:

Tweet IndexElement::getTweet(int i) const{
    if(i>=size){
        return Tweet();
    } else {
        cout << array[i].getID();  
        return array[i];  // this actually works (i.e. it don't crashes on this line)
    }
}  // when I set a breakpoint on this line en press continue the program crashes. Don't know why because there's no code and the program also doesn't go to the destructor so it also couldn't be that.

可以肯定的是,这是我的析构函数:

IndexElement::~IndexElement(){
    delete[] array;
}
Tweet::~Tweet(){
    delete[] tags;
}

我做错了什么,但我不知道是什么。

中的参数是一个传递值,它是堆栈上的本地副本:

void addTweet(Tweet tweet); // tweet will be freed when leaving the function

改为执行以下任一操作:

void addTweet(const Tweet& tweet); // assumes there is a copy constructor for Tweet
void addTweet(Tweet* tweet);       // will not retain the Tweet object

除非您将此作为练习,否则我强烈建议您在列表中使用std::vector,而不是原始指针。

最新更新