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

所属分类: 软件编程 / C 语言 阅读数: 47
收藏 0 赞 0 分享

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修饰成员函数,也属于函数重载的一种范畴。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

更多精彩内容其他人还在看

详解C++ string字符串类

这篇文章主要介绍了C++ string字符串类,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

C++单例类模板详解

这篇文章主要介绍了C++单例类模板,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

C语言实现数据结构迷宫实验

这篇文章主要为大家详细介绍了C语言实现数据结构迷宫实验,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C语言数据结构之迷宫问题

这篇文章主要为大家详细介绍了C语言数据结构之迷宫问题,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C语言数据结构之迷宫求解问题

这篇文章主要为大家详细介绍了C语言数据结构之迷宫求解问题,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C语言实现小学生考试系统

这篇文章主要为大家详细介绍了C语言实现小学生考试系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C语言实现小学生随机出题测试计分

这篇文章主要为大家详细介绍了C语言实现小学生随机出题测试计分,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

C语言实现小学生计算机辅助教学系统

这篇文章主要为大家详细介绍了C语言实现小学生计算机辅助教学系统,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

详解C++中构造函数,拷贝构造函数和赋值函数的区别和实现

这篇文章主要介绍了C++中构造函数,拷贝构造函数和赋值函数的区别和实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
收藏 0 赞 0 分享

C语言清除scanf()缓存的案例讲解

今天小编就为大家分享一篇关于C语言清除scanf()缓存的案例讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
收藏 0 赞 0 分享
查看更多