【问题标题】:shadows a parameter when single parameter on constructor构造函数上的单个参数时隐藏参数
【发布时间】:2013-08-21 01:25:37
【问题描述】:

您好,我正在编写简单的类,然后是 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' 的声明遮蔽了参数'

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

【问题讨论】:

    标签: c++ constructor shadow


    【解决方案1】:

    不过,很可能这两个版本都不能满足您的需求!代码

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

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

    Shape(a);
    

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

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

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

    【讨论】:

    • 上一个和网上的例子完全一样。并且它仍然无法在 Shape(a) 前面添加“:”。有什么建议吗?
    • @user842589:注意括号的确切位置:变化不仅仅是在Shape前面添加一个冒号!您需要在构造函数主体之前的成员初始化器列表中提及需要初始化的基类(和成员)。我可以使用原始代码重现您的错误,并且我的更改确实修复了它。如果第一个示例与 Web 完全一样,那么您选择了一个错误的示例来源,因为它的行为与我所说的一样,我很确定这不是您想要的。
    【解决方案2】:

    因为在单参数编译器中将它作为对象名称并创建一个对象,所以它会产生冲突。

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 2023-03-17
      • 1970-01-01
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      相关资源
      最近更新 更多