我已经设置了两个类,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我做错了什么?
怎样才能达到我想要的结果?
发布于 2016-02-25 17:08:58
您的程序显示出未定义的行为。
int m_Decibels[];将指针声明为int,并且不为要指向的指针分配任何内存。指针在类构造函数中仍然未初始化(因为您没有初始化它)。以后你做的时候
m_Decibels[0]= decibel1;
m_Decibels[1]= decibel2;您是取消引用这个指针,这是一个no-no。要解决这个问题,您可以使用一个固定大小的数组:
int m_Decibels[2];问题的另一面是,您将从您的Dog值中返回一个getDog实例。当您在这个特定实例上设置分贝时,它对类的原始dog成员没有任何影响。要解决这个问题,您可能需要通过引用返回对象,如下所示:
Dog& getDog(); // and corresponding change in the definitionhttps://stackoverflow.com/questions/35633743
复制相似问题