循环通过成员数组给出错误的值
问题描述:
我已经设置了两个类Dog
和AnotherDog
。 Dog
并不意味着它是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()
打印10
和100
,与指数一起。
相反,我得到这个:
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
'INT m_Decibels [];'无效。你需要为数组指定一个大小(或者更好,使用'std :: vector')。 – crashmstr
使用std :: vector而不是int [] –
pm100
@crashmstr,它有点有效。有一个古老的神秘规则允许你以这种方式定义结构的最后一个成员 - 并且它可以用作超越结构的内存指针 - 一些编译器仍然允许它。 – SergeyA