【发布时间】:2016-06-08 14:34:57
【问题描述】:
我设置了两个类,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[];无效。您需要指定数组的大小(或者更好的是,使用std::vector)。 -
在 int[] 中使用 std::vector
代替 -
@crashmstr,它有点有效。有一个古老的神秘规则允许以这种方式定义结构的最后一个成员 - 然后它可以用作指向结构之外的内存的指针 - 一些编译器仍然允许它。
-
不相关:为什么不创建 1 个狗类,创建 2 只不同的狗,或者给狗一个相互交互的方法,或者让拥有两只狗的对象以某种方式协商它们之间的交互?
标签: c++ arrays class oop member