我设置了两个类,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
关于c++ - 通过成员数组循环给出错误的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35633743/