通过基类shape对象的引用调用虚函数area()来实现多态性。c++
时间: 2024-02-26 09:54:41 浏览: 20
是的,C++中的多态性可以通过基类的指针或引用调用虚函数来实现。具体来说,在基类中声明一个虚函数,派生类可以覆盖该函数,使得在通过基类指针或引用调用该函数时,实际执行的是派生类中的函数。这样就可以实现多态性,即同一函数在不同情况下表现出不同的行为。例如,如果定义一个Shape基类,其中包含虚函数area(),然后派生出Rectangle和Circle类并分别重载area()函数,那么通过Shape类的指针或引用调用area()函数时,实际执行的是Rectangle或Circle类中的函数,具体取决于指针或引用所指向的对象类型。
相关问题
如果函数的参数是基类对象或基类对象的引用,函数调用时的实参可以是派生类对象。举个代码解释一下
当函数的参数是基类对象或基类对象的引用时,可以传入派生类对象作为参数,这是因为派生类继承了基类的所有成员,包括成员函数和成员变量,因此可以被当做基类对象来使用。以下是一个简单的C++代码示例:
```cpp
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
int main( ) {
Shape *shape;
Rectangle rec(10,7);
shape = &rec;
// 调用 Rectangle 的 area 函数
shape->area();
return 0;
}
```
在上面的代码中,首先定义了一个基类 `Shape`,其中包含了一个 `area()` 函数,然后定义了一个派生类 `Rectangle`,重写了 `area()` 函数,并且在其中输出了一个字符串 "Rectangle class area :",最后在 `main()` 函数中,定义了一个 `Shape` 指针 `shape` 和一个 `Rectangle` 对象 `rec`,并且将 `rec` 的地址赋给了 `shape`,然后通过调用 `shape->area()` 函数来调用 `Rectangle` 类的 `area()` 函数。因为 `shape` 指向的是一个 `Rectangle` 对象,所以最终输出的结果是 "Rectangle class area :"。
可以看到,尽管 `shape` 的类型是 `Shape`,但是它可以指向一个派生类对象,并且可以调用派生类的成员函数。这也说明了可以将派生类对象当做基类对象来使用,这就是多态性的体现。
c++如何使用基类对象
在 C++ 中,可以使用基类对象来创建派生类对象,这就是面向对象编程中的多态性。具体来说,如果一个类是另一个类的派生类,则可以使用基类对象来引用该派生类对象。
下面是一个简单的例子:
```c++
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a=0, int b=0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
int main() {
Shape *shape;
Rectangle rec(10,7);
shape = &rec;
// 调用矩形的求面积函数 area
shape->area();
return 0;
}
```
在这个例子中,我们定义了一个基类 `Shape`,和一个派生类 `Rectangle`。`Rectangle` 类继承自 `Shape` 类,并重载了 `area()` 函数。
在 `main()` 函数中,我们定义了一个指向 `Shape` 类的指针 `shape`,并将其指向一个 `Rectangle` 类的对象 `rec`。然后我们调用 `shape` 的 `area()` 函数,这时会根据对象实际所属的类型来调用相应的函数,也就是调用 `Rectangle` 类中的 `area()` 函数。
这就是使用基类对象来引用派生类对象的基本方法。