栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C/C++知识点

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C/C++知识点

友元函数

在定义一个类的时候,可以把一些函数(全局函数和其他类的成员函数)声明为友元,这些函数就成为该类的友元函数,在友元函数内部就可以访问该类对象的私有成员。

将全局函数声明为友元:friend 返回值类型 函数名(参数列表);
将其他类的成员函数(不是私有成员函数)声明为友元:friend 返回值类型 其他类的类名::成员函数名(参数列表);

 
友元类 

一个类A可以将另一个类B声明为自己的友元,类B的所有成员函数就都可以访问类A对象的私有成员。

在类定义中声明友元类:friend class 类名;

虚函数

在基类中使用关键字 virtual 声明的函数,在派生类中重新定义积累中定义的虚函数时,会告诉编译器不要静态链接到该函数。

class Shape 
{
	protected:
		int width, height;
	public:
		Shape(int a = 0, int  b = 0)
		{
			width = a;
			height = b;
		}
		virtual int area() 
		{
			cout << "Parent class: " << endl;
			return 0;
		}
};

class Rectangle: public Shape
{
	public:
		Rectange(int a=0, int b= 0):Shape(a, b) { }
		int area() 
		{
			cout << "Rectangle class area: " << endl;
			return (width*height);
		}
};

class Triangle: public Shape
{
	public:
		Triangle(int a=0, int b=0): Shape(a, b) { }
		int area()
		{
				cout << "Triangle class area: " << endl;
		}
};
纯虚函数

在基类中不能对虚函数给出有意义的实现,就会用到纯虚函数。

class Shape
{
	protected:
		int width, height;
	public:
		Shape(int a = 0, int b = 0)
		{
			width = a;
			height = b;
		}
		virtual int area() = 0; //纯虚函数
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号