0

为什么我在以下代码片段中收到 UMR(未初始化内存读取)错误。调用派生类的复制构造函数时出现 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;
}

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

4

2 回答 2

1

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

于 2012-11-26T11:40:14.503 回答
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? 

为什么用派生的::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?
   }  
于 2012-11-26T11:45:18.050 回答