【C++进阶知识】C++多态性


C++多态性

C++是一种基于对象的编程语言,具有许多强大的特性,包括多态性。多态性是指对象的不同性质可以表现为相同的行为。在C++中,有两种类型的多态性:编译时多态性和运行时多态性。

编译时多态性

编译时多态性是通过函数重载和模板实现的。函数重载是指在同一作用域内定义了多个名称相同但参数类型不同的函数。C++编译器会根据函数调用中的参数类型来选择调用哪个函数。例如:

void print(int num) {
    cout << "Integer: " << num << endl;
}

void print(double num) {
    cout << "Double: " << num << endl;
}

int main() {
    int a = 5;
    double b = 3.14;
    print(a);
    print(b);
    return 0;
}

输出结果为:

Integer: 5
Double: 3.14

模板是一种通用的编程机制,可以用来创建具有相同代码结构但不同数据类型的函数或类。例如:

template<typename T>
void print(T num) {
    cout << "Value: " << num << endl;
}

int main() {
    int a = 5;
    double b = 3.14;
    print(a);
    print(b);
    return 0;
}

输出结果与上面的例子相同。

运行时多态性

运行时多态性是通过虚函数和继承实现的。虚函数是指在基类中声明为虚函数的函数,在派生类中可以被重写,派生类对象调用该函数时,将会调用派生类中的函数,而不是基类中的函数。例如:

class Shape {
public:
    virtual void draw() {
        cout << "Drawing a generic shape." << endl;
    }
};

class Rectangle : public Shape {
public:
    void draw() {
        cout << "Drawing a rectangle." << endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Drawing a circle." << endl;
    }
};

int main() {
    Shape* shape1 = new Rectangle();
    Shape* shape2 = new Circle();
    shape1->draw();
    shape2->draw();
    return 0;
}

输出结果为:

Drawing a rectangle.
Drawing a circle.

继承是指派生类可以继承基类中的成员变量和成员函数。例如:

class Animal {
public:
    void speak() {
        cout << "Generic animal sound." << endl;
    }
};

class Dog : public Animal {
public:
    void speak() {
        cout << "Bark!" << endl;
    }
};

int main() {
    Animal* animal1 = new Animal();
    Animal* animal2 = new Dog();
    animal1->speak();
    animal2->speak();
    return 0;
}

输出结果为:

Generic animal sound.
Bark!

应用案例

多态性可以应用于很多场景,例如图形界面编程中的控件、游戏开发中的角色和NPC等等。以下是一个简单的应用案例:

class Shape {
public:
    virtual void draw() = 0;
};

class Rectangle : public Shape {
public:
    void draw() {
        cout << "Drawing a rectangle." << endl;
    }
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Drawing a circle." << endl;
    }
};

int main() {
    vector<Shape*> shapes;
    shapes.push_back(new Rectangle());
    shapes.push_back(new Circle());
    for (int i = 0; i < shapes.size(); i++) {
        shapes[i]->draw();
    }
    return 0;
}

输出结果为:

Drawing a rectangle.
Drawing a circle.

在此示例中,我们使用了纯虚函数和向量容器来管理多个形状对象。无论是矩形还是圆形,都可以通过调用相同的draw()函数来绘制。

总之,C++的多态性是一种非常有用的编程机制,可以提高代码的重用性和灵活性。建议在适当的情况下使用多态性来优化代码结构和提高程序效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文斗士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值