我正在尝试理解虚函数。如何使我的 put() 函数成为虚拟函数?这需要对代码进行哪些更改?
#include <iostream>
#include <string>
using namespace std;
class Circle
{
public:
Circle(double radius) {this->radius = radius; }
void put() const {cout << "Radius = " << radius;}
private:
double radius;
};
class ColoredCircle: public Circle
{
public:
ColoredCircle(double radius, string color);
void put() const;
private:
string color;
};
ColoredCircle::ColoredCircle(double radius, string color)
: Circle(radius), color(color) {}
void ColoredCircle::put() const
{
Circle::put();
cout << " Color = " << color;
}
int main()
{
ColoredCircle redCircle(100., "red");
Circle* circle1 = &redCircle;
circle1->put();
cout << endl;
Circle circle(50.);
Circle* circle2 = &circle;
circle2->put();
cout << endl;
std::cin.get();
return 0;
}