您好,我正在编写简单的类,然后是 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
子对象!相反,它使用参数 a
和 b
创建一个 Shape
类型的临时对象。一个参数版本做类似的事情:
Shape(a);
定义了一个名为a
的Shape
类型的默认构造对象。您可能打算使用初始化列表将构造函数参数传递给 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/