c++基础回顾之虚拟函数与友元函数

类的成员函数

#include<iostream> // c++标准头文件
#include<stdio.h> // C语言标准头文件,包含".h"
#include<ctime>
#include<opencv2/opencv.hpp>
// 命名空间,避免命名污染  
using namespace std;
using namespace cv;
class Girlfriend
{
	int d = 4; // 默认私有属性
// 类内部、类成员函数、继承类均可访问
public:// 共有属性

	int a = 1;
	int age;
	// 构造函数
	Girlfriend() {
		cout << "默认构造函数" << endl;
	}
	Girlfriend(int age){
		cout << "包含参数的构造函数," << endl;
	}
	~Girlfriend() {
		cout << "析构函数" << endl;
	}
	void test(){}
// 可由类的成员函数和友元(类或函数)使用
protected://保护属性

	int b = 1;
// 仅类内部成员可以访问
private: // 私有属性
	int c = 1;
// 友元函数
friend void ChangePrivate(Point & );
};
void ChangePrivate(Point & i) {i.m_i++;}

int main()
{
	Girlfriend mm;
	Girlfriend MM1;
	Girlfriend* p = new Girlfriend(12);
	// 访问成员变量
	p->test();

	return 0;
}

友元函数

友元函数:一个不为类成员的函数,但它可以访问类的私有和受保护的成员

友元函数不被视为类成员;它们是获得了特殊访问权限的普通外部函数。 友元不在类的范围内,除非它们是另一个类的成员,否则不会使用成员选择运算符(. 和 ->)调用它们。 friend 函数由授予访问权限的类声明。 可将 friend 声明放置在类声明中的任何位置。 它不受访问控制关键字的影响。

虚拟函数

对于某些函数,当基类希望派生类重新定义合适自己的版本时,基类就把这些函数声明为虚函数

#include <iostream>
#include <string>
using namespace std;
//  基类
class dog
{
public:
   dog()
   {
      _legs = 4;
      _bark = true;
   }

   void setDogSize(string dogSize)
   {
      _dogSize = dogSize;
   }
   // 虚拟函数,在子类中进行重写
   virtual void setEars(string type)      // virtual function
   {
      _earType = type;
   }

private:
   string _dogSize, _earType;
   int _legs;
   bool _bark;
};
#子类
class breed : public dog
{
public:
   breed( string color, string size)
   {
      _color = color;
      setDogSize(size);
   }

   string getColor()
   {
      return _color;
   }

   // virtual function redefined:重写虚拟函数
   void setEars(string length, string type)
   {
      _earLength = length;
      _earType = type;
   }

protected:
   string _color, _earLength, _earType;
};

int main()
{
   dog mongrel;
   breed labrador("yellow", "large");
   mongrel.setEars("pointy");
   labrador.setEars("long", "floppy");
   cout << "Cody is a " << labrador.getColor() << " labrador" << endl;
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云朵不吃雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值