在构造函数上的单个参数时隐藏参数

use*_*589 0 c++ constructor shadow

嗨,我正在编写简单的类,然后是web中的示例代码.此代码工作正常,没有错误.

class Shape{
      protected:
              int width,height;

      public:
             Shape(int a = 0, int b=0)
             {
             width = a;
             height = b;         
                       }

};
class regSquare: public Shape{
      public:
             regSquare( int a=0, int b=0)
             {
              Shape(a, b);
             }    
};
Run Code Online (Sandbox Code Playgroud)

但是当我改变我的只有一个参数的构造函数,如

class Shape{
      protected:
              int width;
      public:
             Shape(int a = 0)
             {
             width = a;

                       }

};
class regSquare: public Shape{
      public:
             regSquare(int a = 0)
             {
              Shape(a);
             }    
};
Run Code Online (Sandbox Code Playgroud)

这种按摩发生了错误

'错误:'a'声明参数的声明'

我不知道我的代码有什么问题

Die*_*ühl 6

但是,很可能这两个版本都没有你想要的版本!代码

regSquare(int a = 0, int b = 0) {
    Shape(a, b);
}
Run Code Online (Sandbox Code Playgroud)

难道没有初始化Shape你的子对象regSquare的对象!相反,它Shape使用参数a和创建一个类型的临时对象b.一个参数版本执行类似的操作:

Shape(a);
Run Code Online (Sandbox Code Playgroud)

定义一个Shape名为的默认构造对象a.您可能打算使用初始化列表将构造函数参数传递给Shape子对象,例如:

reqSquare(int a = 0, int b = 0)
    : Shape(a, b) {
}
Run Code Online (Sandbox Code Playgroud)

要么

regSquare(int a = 0)
   : Shape(a) {
}
Run Code Online (Sandbox Code Playgroud)