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

标签 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

我做错了什么?

如何达到我想要的结果?

最佳答案

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

 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

关于c++ - 通过成员数组循环给出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35633743/

相关文章:

C++ 和 pin 工具——非常奇怪的 IF 语句双变量问题

arrays - 在Matlab数组中找到模式开始的索引

java - Eclipse 中如何调用另一个项目的类?

c++ - 存储字符数组

VB.NET 创建一个带有可选输入的类

C++ const 函数错误

c++ - 具有显式析构函数和 std::unique_ptr<> 成员的类不能在 std::vector<> 中使用?

c++ - 静态变量 undefined reference

c++ - GCC libstdc++ 配置文件模式的替代方案

arrays - 将字符串拆分为数组(以 "\"分隔)