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

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


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

查看所有标签

猜你喜欢:

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

Pro Git (Second Edition)

Pro Git (Second Edition)

Scott Chacon、Ben Straub / Apress / 2014-11-9 / USD 59.99

Scott Chacon is a cofounder and the CIO of GitHub and is also the maintainer of the Git homepage ( git-scm.com ) . Scott has presented at dozens of conferences around the world on Git, GitHub and the ......一起来看看 《Pro Git (Second Edition)》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

URL 编码/解码
URL 编码/解码

URL 编码/解码