为什么我在以下代码段中收到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;
}
任何人都可以知道实施有什么问题吗?
答案 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?
}