首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环通过成员数组提供错误的值。

循环通过成员数组提供错误的值。
EN

Stack Overflow用户
提问于 2016-02-25 17:06:17
回答 1查看 106关注 0票数 0

我已经设置了两个类,DogAnotherDogDog不是AnotherDog的基类。

AnotherDog中,我有一个Dog对象。在该Dog对象中是一个成员数组。当一个AnotherDog对象调用它的Dog成员时,成员循环通过它的成员数组,我得到错误的结果。

代码语言:javascript
复制
#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

相反,我得到了这个:

代码语言:javascript
复制
0 0
1 4196480

我做错了什么?

怎样才能达到我想要的结果?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-25 17:08:58

您的程序显示出未定义的行为。

代码语言:javascript
复制
 int m_Decibels[];

指针声明为int,并且不为要指向的指针分配任何内存。指针在类构造函数中仍然未初始化(因为您没有初始化它)。以后你做的时候

代码语言:javascript
复制
m_Decibels[0]=  decibel1;
m_Decibels[1]=  decibel2;

您是取消引用这个指针,这是一个no-no。要解决这个问题,您可以使用一个固定大小的数组:

代码语言:javascript
复制
int m_Decibels[2];

问题的另一面是,您将从您的Dog值中返回一个getDog实例。当您在这个特定实例上设置分贝时,它对类的原始dog成员没有任何影响。要解决这个问题,您可能需要通过引用返回对象,如下所示:

代码语言:javascript
复制
   Dog& getDog(); // and corresponding change in the definition
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35633743

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档