如何初始化成员变量 [英] How to Initialize Member Variables

查看:117
本文介绍了如何初始化成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能是一个简单的问题,有人在那里,但我做错了在下面的例子?我试图建立一个全局类,其中包含其他类的实例化...我认为我会错误地归结到下面的例子。得到seg故障,如同* b从未创建。先感谢!

Probably an easy question for someone out there, but what am I doing wrong in the below example? I'm trying to build a global class which contains instantiations of other classes within... I think where I'm going wrong boils down to the below example. Getting a seg fault, as if *b is never created. Thanks in advance!!

#include <iostream>

using namespace std;

class A;
class B;

class B
 {
   public:
   B()
   {
       b = 99;
   }
   ~B();

  int Getb() {return b; }
  void Setb (int x) { b = x; }

  private:
  int b;

};

class A
{
    public:
   A()
    {
        B *b = new B;
    }
    ~A();

    B * b;

    void Printout()
    {
        cout<<b->Getb()<<endl;
    }
    private:

};

int main()
{
A *a = new A;
a->Printout();
cin.get();
}


推荐答案

A() {
    B *b = new B;
}

B * b;

在构造函数中声明一个新的局部变量 B 的地址,然后被遗忘!

In the constructor you're declaring a new local variable that gets assigned the address of the freshly allocated B, and then forgotten!

实例字段 b

The instance field b is never assigned to because it is shadowed by the local variable of the same name in the constructor.

A() {
    b = new B;
}

这篇关于如何初始化成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆