友元
1.1为什么要使用友元函数
在实现类之间数据共享时,减少系统开销,提高效率。如果类A中的函数要访问类B中的成员(例如:智能指针类的实现),那么类A中该函数要是类B的友元函数。
具体来说:为了使其他类的成员函数直接访问该类的私有变量。即:允许外面的类或函数去访问类的私有变量和保护变量,从而使两个类共享同一函数。
实际上具体大概有下面两种情况需要使用友元函数:(1)运算符重载的某些场合需要使用友元。(2)两个类要共享数据的时候。
1.2使用友元函数的优缺点
优点:能够提高效率,表达简单、清晰。
缺点:友元函数破环了封装机制,尽量不使用成员函数,除非不得已的情况下才使用友元函数。
B类中嵌A类对象,但是B的成员函数无法直接访问A的私有成员
1.某类中嵌套了一个类,该类普通成员函数可以直接访问
2.普通函数可以访问那个类中的数据
实现:
- 友元函数(普通函数+其他了类的成员函数)
<1>friend <类型标识符> <友元函数名> (参数表)
<2>friend <类型标识符> 类名 ::<友元函数名> (参数表)
- 简单使用,普通函数
<1>
class cpoint
{
doule x, y;
public:
}
重载运算符
//重载+运算符
const Integer operator+(const Integer & other) const;
const Integer operator-(const Integer & other) const;
const Integer operator*(const Integer & other) const;
const Integer operator/(const Integer & other) const;
const Integer operator%(const Integer & other) const;
//重载赋值运算符,需要const修饰函数
//num4.operator = (num3)
const Integer & operator = (const Integer & other);
//二元运算符建议采用友元得方式重载
friend const Integer operator + (int intvalue, const Integer & other)
//流运算符一般智能使用友元函数进行重载
friend ostream & operator << (ostream & out , const Integer & num);
//友元函数不需要使用域运算符了
const Integer operator +( int intvalue , const Integer & other)
{
return Integer(intvalue + other.m_value);
}
//流运算符友元函数重载
继承和派生
在C++中 代码重用通过继承机制实现
- 继承就是在一个已有类得基础上,建立一个新类
- 类可升级可维护
- 基类定义了公共得内容,方便统一修改
- 代码得可重用性:类库
- 添加新类,新成员方便
注意:
- 派生类对象包含了基类得数据成员,派生类继承了积累得实现
- 派生类对象可以使用基类得非私有函数
- 派生类需要自己的构造函数
- 派生类可以添加额外的数据成员和函数
1、公有继承
//hero.h文件
#ifndef HER0_H
#define HER0_H
#include <iostream>
#include <string>
using namespace std;
/**
*英雄基类/父类
*/
class Hero
{
private:
string m_NickName;
int m_lever;
int m_MaxLife;
int m_CurrLife
public:
Hero();
void Move();
}
class Warrior :public Hero
{
//战士特有的成员和函数
}
class Archmage :public Hero
{
//法师特有的成员和函数
}
#endif //HER0_H
继承方式提供程序员对类进行封装的机制
- 公有继承:(无法访问基类的私有,维持基类的访问权限)
- 私有继承:(除了基类的私有成员,其他成员都会改为私有)
- 受保护继承:(无法访问基类的私有,基类的共有变为受保护)
不管使用哪种继承,派生类都不能访问基类的私有成员(除非改为共有成员)
private:私有
public:共有
prtected:受保护的