过载运算符>>对于特定的类

时间:2013-09-16 20:25:35

标签: c++ qt

我为>>实现了运算符重载和<<

似乎<<

没有问题

但是对于实现运算符>>如下,我收到了运行时错误

QDataStream & operator>> (QDataStream & stream, chromosome & myChromosome){

    myChromosome = chromosome();

    double len, wing1, wing2, tail, head;
    int index;

    stream >> head >> len >> tail >> wing1 >> wing2 >> index;

    myChromosome.setChromosomeHeadLength(head);
    myChromosome.setChromosomeLength(len);
    myChromosome.setChromosomeTailLength(tail);
    myChromosome.setChromosomeWing1Length(wing1);
    myChromosome.setChromosomeWing2Length(wing2);
    myChromosome.setIndex(index);

    return stream;
}

当我到达myChromosome.setChromosomeHeadLength(head);

时,我调试这个部分,并编程停止(运行时错误)

修改 染色体代码:

chromosome::chromosome()
{
    chromosomeLength = 0;
    chromosomeHeadLength = 0;
    chromosomeTailLength = 0;
    chromosomeWing1Length = 0;
    chromosomeWing2Length = 0;
    index = 0;

    topLeftX=0;
    topLeftY=0;
    bottomRightX=0;
    bottomRightY=0;
}
...
void chromosome::setChromosomeLength(double lenght){
    chromosomeLength = lenght;
}

void chromosome::setChromosomeHeadLength(double lenght){
    chromosomeHeadLength = lenght;
}

void chromosome::setChromosomeTailLength(double lenght){
    chromosomeTailLength = lenght;
}

void chromosome::setChromosomeWing1Length(double lenght){
    chromosomeWing1Length = lenght;
}

void chromosome::setChromosomeWing2Length(double lenght){
    chromosomeWing2Length = lenght;
}

当我运行程序时,错误是: myProgram.exe已停止工作

当我调试它时,我得到了这个 enter image description here

编辑2: 更多代码,使用运算符>>和<<

void TabView::save(QDataStream &stream)
{

    stream << numberOfChromosomes;

    for(int i = 0; i < numberOfChromosomes; i++){
        stream << chromosomes[i];
    }
...
}

bool TabView::load(QDataStream &stream){    

    stream >> numberOfChromosomes;

    for(int i = 0; i < numberOfChromosomes; i++){
        stream >> chromosomes[i];
    }
...
}

任何想法都表示赞赏。

1 个答案:

答案 0 :(得分:1)

QDataStream & operator>> (QDataStream & stream, chromosome & myChromosome){

myChromosome = chromosome();

...省略

这部分对我来说真的很不错。在我看来,你正在传递对myChromosome的引用,然后直接在它上面构建一个新引用。我不确定这是否是分段错误的位置,但如果您使用动态分配的内存,它看起来像(正如其他成员已经注意到的那样)违反了 RULE OF THREE

由于您没有为类myChromosome提供标头定义,我唯一的猜测是,当您使用赋值运算符创建新类时,您将使某些内存空间无效。请记住,这是猜想,因为您未提供.h实施。