【问题标题】:initialize variable in constructor在构造函数中初始化变量
【发布时间】:2015-02-19 01:38:48
【问题描述】:
 #include <iostream>

using namespace std;

class aclass
{
   public:

   int a;
};

class cclass: public aclass
{
   public:  
   cclass()
   {
      a= //what do i write here//
   }
}

class bclass : public aclass 
{
public:
   bclass()
   {
      a=9;     //a is not constant here. I have just taken it const for simplicity.
   }

 int func();
};


int bclass::func()
{
   cclass * ob;
   ob = new cclass(); 
}

如何使 cclass 对象的变量 a 的值等于创建它的 bclass 对象(cclass 的对象)的 a 值。我可以在函数 func() 中做到这一点 通过做

ob->a = a;

但是在 cclass 的构造函数中我该怎么做呢?

【问题讨论】:

  • 我会重新阅读书中的那一章
  • 我写了一个答案,但随后将其删除,因为您似乎不了解您尝试编写的代码的基本原理。你在这里的目标是什么?
  • 在您拥有new cclass 的地方,cclass 类型尚未声明,因此这不是真正的代码
  • @RyanHaining 在运行时,将创建 bclass 的不同对象,这些对象将具有不同的 a 值,这些对象(bclass 的对象)将创建 cclass 的相应对象。通过“对应”,我的意思是 cclass 的 a 的值将等于 bclass 的对象的 a 的值,bclass 的对象创建了一个 cclass 的对象。

标签: c++ oop object inheritance constructor


【解决方案1】:

您需要将其作为 func() 方法的参数传递。

ob = new cclass(this.a);

【讨论】:

  • 我没有反对这一点,它的方向是正确的,但在 C++ 中必须写 this-&gt;a,或者只是 a;符号 this.a 不会编译。
【解决方案2】:

关键字“base”允许访问父属性

base.a = 9

更多信息请查看this

【讨论】:

  • -1 标准 c++ 中没有关键字 base
【解决方案3】:

你必须将 bclass 对象传递给 cclass 构造函数:-

class cclass: public aclass
{
   cclass(const bclass& b)
   {
      a = b.a;
   }
}

如果您忽略代码中的其他特性。

【讨论】:

    【解决方案4】:

    您可以在其定义中定义一个指向创建类“cclass”的类的指针:

    class cclass: public aclass
    {
        bclass * bclass_ref;
        cclass(bclass * ref)
        {
            bclass_ref = ref;
            a = b_class_ref->a;
        }
    }
    

    然后您将 this 关键字添加到类 'bclass' 范围内的类 'cclass' 的定义中:

    ob = new cclass(this);
    

    注意:某些编译器可能会在类“cclass”的构造函数上抛出错误,您只需将构造函数公开即可。

    编辑:我自己测试了代码,你需要在函数'bclass::func'的定义之前添加类'cclass'的定义

    【讨论】:

    • 您可能正在使用一个额外的指向 bclass 的指针。我做了和你写的一样的事情,但我没有使用额外的 bclass_ref 指针,而是直接做 a= ref->a。
    • 是的,我在函数'bclass::func'之外定义了bclass_ref以供将来参考,我的错,因为它在App退出函数时被破坏......
    猜你喜欢
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多