为什么我在下面的代码片段中收到UMR(unInitialized Memory Read)错误

时间:2012-11-26 11:24:09

标签: c++

为什么我在以下代码段中收到UMR(unInitialized Memory Read)错误。 调用派生类的副本构造函数时,我收到UMR错误

class base{
public :

    base(int);
    int id;

    int getid()
    {
        return id;
    }
};

base::base(int a)
{
    id = a;
}

class derived:public base{
public :
    derived(derived &);
    int inum;

    int getnum()
    {
        return inum;
    }

};

derived::derived(derived &d):base(d.getnum()) // UMR Error
{
    inum = id;
}

任何人都可以知道实施有什么问题吗?

2 个答案:

答案 0 :(得分:1)

派生类永远不会初始化inum变量。错误消息告诉你。 d.getnum()会返回未初始化的inum变量。

答案 1 :(得分:0)

我认为你不能编译你的代码,下面是一些问题:

class derived:class base{
               ^^^-> public

应该是:

class derived : public base

更改int getnum(); to int getnum() const;

derived::derived(derived &d):base(d.getnum) // UMR Error
                                         ^^^ function call? 

为什么用derived :: inum初始化base :: id?

应该是:

   derived::derived(const derived &d) : base(d) // initialize base with base
   {
                    ^^^  copy constructor has const 
      inum = d.inum;  // initialize derived member
      // inum = id;  why you assign id back to inum again?
   }