c++ 形参是父类的引用,实参却是子类对象
时间: 2024-09-18 20:06:47 浏览: 74
在 C++ 中,当形参是父类的引用,而实参是子类的对象时,这种情况称为“向下转型”或“隐式转换”。这是因为尽管函数声明中使用的形参是父类类型的,但在实际调用时,如果传入的是子类的对象,编译器会自动将子类对象转换为父类类型的指针或引用。
例如,假设有一个基类 `Shape` 和两个派生类 `Circle` 和 `Square`:
```cpp
class Shape {
public:
virtual void draw() const { cout << "Drawing a shape." << endl; }
};
class Circle : public Shape {
public:
void draw() const override { cout << "Drawing a circle." << endl; }
};
class Square : public Shape {
public:
void draw() const override { cout << "Drawing a square." << endl; }
};
void printShape(const Shape& s) {
s.draw();
}
int main() {
Circle circle;
Square square;
// 尽管printShape接受的是Shape的引用,但circle和square都是其子类对象
printShape(circle); // 输出: Drawing a circle.
printShape(square); // 输出: Drawing a square.
return 0;
}
```
这里,`printShape` 函数可以接受任何 `Shape` 类型的引用,而当我们传入 `Circle` 或 `Square` 对象时,它们的 `draw` 方法会被正确地调用,体现了 C++ 的多态性。
阅读全文
相关推荐


















