循环通过成员数组会给出错误的值

时间:2016-02-25 17:06:18

标签: c++ arrays class oop member

我已经设置了两个班级DogAnotherDogDog并不是AnotherDog的基类。

AnotherDog中,我有一个Dog对象。在Dog对象中是一个成员数组。当AnotherDog对象调用其Dog成员,然后成员循环通过其成员数组时,我得到错误的结果。

#include <iostream>

class Dog
{
private:
    int m_NumberOfBarks;
    int m_Decibels[];
public:
    Dog();
    ~Dog();

    void setBarkDecibels(int decibel1, int decibel2);
    void loopDecibels();
};

Dog::Dog() : m_NumberOfBarks(2){}
Dog::~Dog(){}

void Dog::setBarkDecibels(int decibel1, int decibel2){
    m_Decibels[0]=  decibel1;
    m_Decibels[1]=  decibel2;
}

void Dog::loopDecibels(){
    for(int i=0; i<m_NumberOfBarks; ++i){
        std::cout << i << ' ' << m_Decibels[i] << std::endl;
    }
}


class AnotherDog
{
private:
    Dog m_Dog;
public:
    AnotherDog();
    ~AnotherDog();

    Dog getDog();
};

AnotherDog::AnotherDog(){
    m_Dog.setBarkDecibels(10, 100);
}
AnotherDog::~AnotherDog(){}

Dog AnotherDog::getDog(){
    return m_Dog;
}


int main(){
    AnotherDog goodDog;
    goodDog.getDog().loopDecibels();
    return 0;
}

我希望void Dog::loopDecibels()与索引一起打印10100

相反,我得到了这个:

0 0
1 4196480

我做错了什么?

如何达到我想要的效果?

1 个答案:

答案 0 :(得分:4)

您的程序显示未定义的行为。

 int m_Decibels[];

向int声明指针,并且不为指向的指针分配任何内存。指针在类构造函数中保持未初始化(因为您没有初始化它)。以后你做

m_Decibels[0]=  decibel1;
m_Decibels[1]=  decibel2;

解除引用这个指针,这是禁忌。要解决此问题,您可以使用固定大小的数组:

int m_Decibels[2];

硬币的另一面是您从Dog按值返回getDog的实例。在此特定实例上设置分贝时,它对类的原始dog成员没有影响。要解决此问题,您可能希望通过引用返回对象,如下所示:

   Dog& getDog(); // and corresponding change in the definition