首页 > 编程 > ASP > 正文

详解C++ 中const修饰虚函数的实例演示

2024-05-04 11:05:19
字体:
来源:转载
供稿:网友

本篇文章是详解C++ 中const修饰虚函数的实例演示,希望通过错新技术频道小编的介绍,我们能够彻底掌握如何使用它,有需要的朋友可以进入下文参考哦。

C++ 中const修饰虚函数实例详解

【1】程序1

#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print();};void Test::print(){ cout << "Test::print()" << endl;}void main(){ // Base* pChild = new Test(); //compile error! // pChild->print();}

【2】程序2

#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print(); void print() const;};void Test::print(){ cout << "Test::print()" << endl;}void Test::print() const{ cout << "Test::print() const" << endl;}void main(){ Base* pChild = new Test(); pChild->print();}/*Test::print() const*/

【3】程序3

#include <iostream>using namespace std;class Base{public: virtual void print() const = 0;};class Test : public Base{public: void print(); void print() const;};void Test::print(){ cout << "Test::print()" << endl;}void Test::print() const{ cout << "Test::print() const" << endl;}void main(){ Base* pChild = new Test(); pChild->print(); const Test obj; obj.print(); Test obj1; obj1.print(); Test* pOwn = new Test(); pOwn->print();}/*Test::print() constTest::print() constTest::print()Test::print()*/

备注:一切皆在代码中。

总结:const修饰成员函数,也属于函数重载的一种范畴。

感谢大家阅读详解C++ 中const修饰虚函数的实例演示的内容,希望能帮助到大家,同时也感谢大家对错新技术频道的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表