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

问题描述:

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

我在做什么错?

我如何获得我想要的结果?

+4

'INT m_Decibels [];'无效。你需要为数组指定一个大小(或者更好,使用'std :: vector')。 – crashmstr

+0

使用std :: vector 而不是int [] – pm100

+0

@crashmstr,它有点有效。有一个古老的神秘规则允许你以这种方式定义结构的最后一个成员 - 并且它可以用作超越结构的内存指针 - 一些编译器仍然允许它。 – SergeyA

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

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 
+0

我已经向阵列添加了一个大小,建议使用@crashmstr。你能告诉我你的意思吗?“当你在这个特定的实例上设置你的分贝时,它对这个班的原狗成员没有影响”?你在说“m_dog”吗? – Username

+1

@用户名,当你按值返回你的'狗'时,你正在返回一份副本。对副本的修改不会影响原创。 – SergeyA

+0

然后,如果我想在'getDog()'调用时修改'm_dog',我应该按地址返回? 'return&m_dog'? – Username