c++ - 当构造函数上的单个参数时隐藏参数

标签 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);
             }    
};

但是当我将构造函数更改为只有一个参数时,例如

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

                       }

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

这次按摩出现错误

'error: declaration of `a' shadows a parameter'

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

最佳答案

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

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

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

Shape(a);

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

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

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

关于c++ - 当构造函数上的单个参数时隐藏参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18347474/

相关文章:

flutter - 如何在 Flutter 中向 TextFormField 添加阴影

uiimageview - 为 UIImageVIew 添加圆角并显示阴影效果

使用 "days"的 C++ 数据类型和函数

c++ - 从 boost 共享内存转储数据的最佳方法

c++ - 使用 push_back 和 getline 时如何减少临时对象?

c++ - 继承构造函数和大括号或等于初始值设定项

c++ - 初始化列表的使用

objective-c - UITextView 阴影不起作用

c++ - 带引用键的 unordered_map

c++ - 带阴影的聚光灯变成方形