为什么派生类成员给出垃圾值

时间:2014-05-14 19:27:02

标签: c++ inheritance

    #include<iostream>

    using namespace std;

    class base
    {
    int i;
    public:
    base()
    {
    i=10;
    cout<<"Base Constructor\n";
    }
    base(base &a)
    {
    cout<<"base Copy Constructor\n";
    a.i=i;

    }

    ~base()
    {
    cout<<"base Destructor\n";
    cout<<i<<endl;
    }

    };

    class derived:public base
    {
    int j;
    public:
    derived()
    {
    j=20;
    cout<<"derived Constructor\n";
    }
    derived(derived &a)
    {
    cout<<"derived Copy Constructor\n";
    a.j=j;
    cout<<j<<endl;
    }

    ~derived()
    {
    cout<<"derived Destructor\n";
    }

    };

    main()
    {
    base obj;
    base obj1=obj;

    derived ob;
    derived ob1=ob;

    }

我是cpp的初学者我试图理解单继承如何表现它的const,dest如何表现但在派生类派生成员中产生垃圾值的问题..可以有人解释我。

2 个答案:

答案 0 :(得分:1)

您的副本构造函数错误。您正在复制到源而不是目标。尝试更换:

base(base &a)
{
  cout<<"base Copy Constructor\n";
  a.i=i;
}

使用:

base(base &a)
{
  cout<<"base Copy Constructor\n";
  i = a.i;
}

derived(derived &a)
{
  cout<<"derived Copy Constructor\n";
  a.j=j;
  cout<<j<<endl;
}

derived(derived &a)
{
  cout<<"derived Copy Constructor\n";
  j=a.j;
  cout<<j<<endl;
}

答案 1 :(得分:0)

您的副本构造函数实现不正确。

您正在修改传入的对象,而不是正在构建的对象。试试这个:

i=a.i;

j=a.j;

在您的副本构造函数中,而不是相反。

这应该(可能)做你想要做的事情,你应该能够看到为什么你当前这样做会导致未初始化的成员变量。