当构造函数上只有一个参数时,会对参数进行阴影处理

shadows a parameter when single parameter on constructor

本文关键字:参数 处理 阴影 构造函数 有一个      更新时间:2023-10-16

Hi我在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);
             }    
};

但是当我把我的改为只有一个构造函数的参数时,比如

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

此按摩发生错误

'错误:"a"的声明遮蔽了参数'

我不知道我的代码出了什么问题

不过,很可能这两个版本都不符合您的要求!代码

regSquare(int a = 0, int b = 0) {
    Shape(a, b);
}

是否初始化regSquare对象的Shape子对象!相反,它使用参数ab创建一个类型为Shape的临时对象。单参数版本的作用类似:

Shape(a);

定义了一个默认构造的类型为Shape的对象,称为a。您可能打算使用初始值设定项列表将构造函数参数传递给Shape子对象,例如:

reqSquare(int a = 0, int b = 0)
    : Shape(a, b) {
}

regSquare(int a = 0)
   : Shape(a) {
}

因为在单参数中,编译器将其作为对象名称并创建对象,所以它正在创建冲突。