C++ 中const修饰虚函数实例详解
程序员文章站
2022-06-15 15:38:05
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修饰成员函数,也属于函数重载的一种范畴。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
下一篇: php访问对象中的成员的实例方法