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

栏目: 编程语言 · ASP.NET · 发布时间: 8年前

内容简介:这篇文章主要介绍了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() const
Test::print() const
Test::print()
Test::print()
*/

备注:一切皆在代码中。

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

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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Machine Learning in Action

Machine Learning in Action

Peter Harrington / Manning Publications / 2012-4-19 / GBP 29.99

It's been said that data is the new "dirt"—the raw material from which and on which you build the structures of the modern world. And like dirt, data can seem like a limitless, undifferentiated mass. ......一起来看看 《Machine Learning in Action》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具