垃圾值 - C++中的继承

Kut*_*u V 2 c++ virtual inheritance constructor abstract

我有一个课程如下:

class base
{
    protected:
        int x;
        int y;
        int z;
    public:
        base(int x, int y, int z)
        {
            x = x;
            y = y;
            z = z;
        }
        virtual void show();
};
Run Code Online (Sandbox Code Playgroud)

我从上面得到了一个类:

class derived : protected base
{
    public:
        int a;
        int b;
        int c;
        derived(int a, int b, int x, int y, int z) : base(x, y, z) //initialising the base class members as well
        {
            cout<<a<<b<<x<<y<<z; //works fine
            a = a;
            b = b;
        }
        void show()
        {
            cout<<a<<b<<x<<y<<z; //show junk values            
        }
        //some data members and member functions
};
Run Code Online (Sandbox Code Playgroud)

在main()中,我使用:

    derived d(1, 2, 3, 4, 5);

    d.show();
Run Code Online (Sandbox Code Playgroud)

数据成员似乎在构造函数中具有合法值.但是,当我使用类似的功能时,即具有相同的可见性模式时,似乎会出现垃圾值.

Luc*_*ore 5

a = a;
b = b;
Run Code Online (Sandbox Code Playgroud)

应该

this->a = a;
this->b = b;
Run Code Online (Sandbox Code Playgroud)

或者,更好的是,使用初始化列表:

derived(int a, int b, int x, int y, int z) : a(a), b(b),  base(x,y,z) 
{
    cout<<a<<b<<x<<y<<z; //works fine
}
Run Code Online (Sandbox Code Playgroud)

你正在做的是自我分配参数,所以成员不会被设置.