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修饰成员函数,也属于函数重载的一种范畴。
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!