运算符重载
一、友元机制
1.友元介绍
·友元是一种允许非类成员函数访问类的非公有成员的一种机制
·可以把一个函数指定为类的友元,也可以把整个类指定为另一个类的友元。
友元函数
友元类
2.友元函数
·友元函数在类作用域外定义,但它需要在类体中进行说明
·为了与该类的成员函数加以区别,定义的方式是在类中用关键字friend说明该函数,格式如下:
friend 类型 友元函数名(参数表)
友元的作用在于提高程序的运行效率
友元函数的注意事项:
·友元函数不是类的成员函数,在函数体中访问对象的成员,必须用对象名加运算符“.”加对象成员名。但友元函数可以访问类中的所有成员(公有的、私有的、保护的),一般函数只能访问类中的公有成员。
·友元函数不受类中的访问权限关键字限制,可以把它放在类的公有、私有、保护部分,但结果一样。
·某类的友元函数的作用域并非该类作用域。如果连友元函数不是另一类的成员函数,则其作用域为另一类的作用域,否则与一般函数相同。
·友元函数破坏了面向对象程序类的封装性,所有友元函数如不是为了必须使用则尽可能少用。或者用其他手段保护封装性。
3.友元类
友元类的注意事项:
·友元关系是单向的
·友元关系不能被传递
·友元关系不能被继承
代码示例:
String.h;
#ifndef _STRING_H_
#define _STRING_H_
class String
{
public:
friend class StringTool;
friend void print(const String &s1); //友元函数
String();
String(char *str);
~String();
void Display();
private:
char *str_;
};
#endif
String.cpp:
#include <iostream>
#include "String.h"
using namespace std;
String::String()
{
cout << "default constructor String!" << endl;
}
String::String(char *str)
{
cout << "constructor String" << endl;
int len = strlen(str) + 1;
str_ = new char(len);
memset(str_, 0, len);
strcpy(str_, str);
}
String :: ~String()
{
cout << "destory String" << endl;
}
void String::Display()
{
cout << str_ << endl;
}
void print(const String& s1)//友元函数
{
cout << s1.str_ << endl;
}
StringTool.h:
#ifndef _STRINGTOOL_H_
#define _STRINGTOOL_H_
#include "String.h"
class StringTool
{
public:
void mystrcat(String& s1, String& s);
};
#endif
StringTool.cpp:
#include <iostream>
#include <string.h>
#include "StringTool.h"
void StringTool::mystrcat(String &s1, String &s)
{
strcat(s1.str_, s.str_);
}
main.c:
#include <iostream>
#include "String.h"
#include "StringTool.h"
using namespace std;
int main()
{
String s1("hello");
print(s1);
//String s2("world");
//StringTool st;
//st.mystrcat(s1, s2);//调用友元类
return 0;
}
运行结果:
二、运算符重载
1.运算符重载介绍
·运算符重载允许把标准运算符(如+、—、*、/、<、>等)应用于自定义数据类型的对象
运算符重载的作用:
·直观自然,可以提高程序的可读性
·体现了C++的可扩充性
·运算符重载仅仅只是为了语法上的方便,它是另一种函数调用方式
·运算符重载,本质上是函数重载
运算符重载的注意事项:
·不要滥用重载,本质上是函数重载
2.运算符重载的实现
(1)成员函数重载
· 成员函数原型格式:
函数类型 operator 运算符(参数表);
·成员函数定义的格式:
函数类型 类名 :: operator 运算符(参数表)
{
函数体;
}
(2)友元函数重载
·友元函数原型的格式:
friend 函数类型 operator运算符(参数表);
·友元函数定义的格式:
函数类型 函数类型 类名::operator 运算符(参数表)
{
函数体;
}
3.运算符重载规则