C++ 中const修饰虚函数实例详解
程序员文章站
2022-03-10 14:34:43
c++ 中const修饰虚函数实例详解
【1】程序1
#include
using namespace std;
cl...
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() const test::print() const test::print() test::print() */
备注:一切皆在代码中。
总结:const修饰成员函数,也属于函数重载的一种范畴。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
上一篇: 哪些菜只有皇上才能吃?原因是什么?
下一篇: asp获取虚拟目录根路径的代码