短小(频繁,且没有循环体)的功能:
1.内联函数:
特点:1.在函数名前加inline关键字;
2.以空间换取时间,编译阶段整个函数体替换调用部分;
2.宏定义:
1.对变量宏定义:
#define 宏名 值
2.带参函数的宏定义
#define 函数名(形参表:不需要类型) 函数体
1.整体思维
2.不进行类型检测
3.传递数据类型
4.多行 \
特殊的函数(类中):
1.内联函数:
隐式内联:将成员函数的定义写在class类的定义中;
显式内联:在声明和定义前加上inline关键字;
2.友元函数:(破坏了类的封装性,访问类的所有成员(包含私有))
声明:1.写在类中 2.在声明前friend关键字
定义和调用:和普通函数相同(友元函数不属于类的成员函数(没有this指针))
友元类:该类的所有成员函数都是友元函数;
1.写法:A是B的友元类(在B类中写上friend class A;)
2.特点:1.不可逆性:A是B的友元类,B不一定是A的友元类;
2.不可传递性:A是B的友元类,B是C的友元类,A不一定是C的友元类;
3.不可继承性:A是B的友元类,C是A的子类,C不一定是B的友元类;
运算符重载:使自定义类型的对象可以进行运算;
1.成员函数:
返回值类型 operator运算符(形参表);
2.友元函数:(参数个数相对于成员函数多1个)
friend 返回值类型 operator运算符(形参表);
注意:
1.能写成成员函数的运算符重载一定可以写成友元,反之不成立;
2.区分前置和后置是在重载后置运算符的形参中写上int;
(int没有实际意义,只是为了区分前后置)
3.当运算符的左表达式不是当前类的对象时,只能写成友元;
(例如输入>> 输出<<)
#pragma once
#include <iostream>
using namespace std;
class Clock
{
public:
Clock(int h = 0,int m = 0,int s = 0);
~Clock();
public:
Clock& operator++();//前置:先自增再运算;
Clock operator++(int);//后置:先运算再自增;//int
Clock operator-(const Clock& other);//减法
//1.返回值&:输入输出流操作
//2.形参&:为了最终返回
//3.只能写成友元:左表达式不是Clock的对象
friend ostream& operator<<(ostream& os,const Clock& c);//重载输出<<运算符
friend istream& operator>>(istream& is, Clock& c);
private:
int hour;//时
int minute;//分
int second;//秒
};
#include "Clock.h"
Clock::Clock(int h,int m,int s)
:hour(h),
minute(m),
second(s)
{
}
Clock::~Clock()
{
}
//前置++
Clock& Clock::operator++()
{
second++;
if (second == 60)
{
minute++;
second = 0;
}
if (minute == 60)
{
hour++;
minute = 0;
}
if (hour == 24)
{
hour = 0;
}
//判断大于等于60
return *this;//返回自身
}
//后置++:
Clock Clock::operator++(int)
{
//1.保存没有改变前的时间
Clock temp = *this;
//2.时间++
second++;
if (second == 60)
{
minute++;
second = 0;
}
if (minute == 60)
{
hour++;
minute = 0;
}
if (hour == 24)
{
hour = 0;
}
//
//
//3.返回没有自增之前的时间
return temp;
}
ostream& operator<<(ostream& os, const Clock& c)
{
os << "时:" << c.hour << "分:" << c.minute << "秒:"
<< c.second;
return os;
}
istream& operator>>(istream& is, Clock& c)
{
cout << "请输入时分秒" << endl;
is >> c.hour >> c.minute >> c.second;
return is;
}
Clock Clock::operator-(const Clock& other)
{
Clock c;
int s1 = hour * 60 * 60 + minute * 60 + second;
int s2 = other.hour * 60 * 60 + other.minute * 60 + other.second;
int c1 = abs(s1 - s2);
c.second = c1 % 60;
c.minute = ((c1 - c.second) / 60) % 60;
c.hour = (((c1 - c.second - c.minute * 60) / 60) / 60) % 24;
return c;
}
----------------------------------
1. 构造函数私有化:防止在类外创建对象
析构函数私有化:防止在类外创建除堆区以外的对象
重载new运算符:防止创建堆区的对象
2.创建静态成员函数:用来创建对象
3.创建静态成员:保存堆区对象的地址