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

Looping thru member array gives wrong values

本文关键字:出错 错误 数组 成员 循环      更新时间:2023-10-16

我设置了两个类,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

我做错了什么?

如何实现我想要的结果?

您的程序表现出未定义的行为。

 int m_Decibels[];

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

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

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

int m_Decibels[2];

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

   Dog& getDog(); // and corresponding change in the definition
相关文章: