一.友元函数
1. 定义:友元是一种允许非类的成员函数访问类的非公有成员的一种机制。
友元函数在类的作用域外定义,但需要在类体中加上关键字friend进行说明。
2. 友元的形式:
l 友元函数
l 友元类
3. 友元的作用
提高程序的效率——类的非公有成员,在类外访问需要通过函数调用和返回来实现,若定义友元函数,则不需要,效率会提高
4. 友元函数的注意事项
1) 友元函数不是类的成员函数,在函数体中访问对象的成员,要用对象名加运算符”.”加对象成员名。
2) 友元函数可以访问类中的所有成员,不受publicprivate protected 的限制
3) 友元函数的作用域不是该类的作用域。
4) 友元函数破坏了类的封装性,尽量少用
Demo
l 友元函数
#ifndef _STRING_H_
#define _STRING_H_
#include <iostream>
using namespace std;
class String
{
public:
String();
~String();
String(char *str);
String& operator=(constString& other);
friend void print(const String &s1);
private:
char *str_;
};
#endif
#include "String.h"
String::String ()
{
cout<< "construct test" <<endl;
str_ = new char('\0');
}
String::~String ()
{
cout<< "destroy construct test"<< endl;
delete [] str_;
}
String::String (char*str)
{
cout<< "default construct test"<< endl;
int len = strlen(str) + 1;
str_ = new char[len];
memset(str_,0,len);
strcpy(str_,str);
}
String& String::operator=(const String& other)
{
if(this ==&other)
{
return *this;
}
int len = strlen(other.str_ ) + 1;
delete [] str_;
str_ = new char[len];
memset(str_,0,len);
strcpy(str_,other.str_);
}
#include "String.h"
void print(const String &s1)
{
cout<< s1.str_ <<endl;
}
int main()
{
String s1("hello");
print(s1);
return 0;
}
l 友元类
#include <iostream>
using namespace std;
class String
{
public:
String();
~String();
String(char *str);
void display();
String& operator=(constString& other);
friend classStringTool;
private:
char *str_;
static int MAX_LEN; //类成员,在String.cpp中进行类外初始化
};
#include "String.h"
int String::MAX_LEN = 0; //一定要在类外初始化
String::String ()
{
cout<< "construct test" <<endl;
str_ = new char('\0');
}
String::~String ()
{
cout<< "destroy construct test"<< endl;
delete [] str_;
}
String::String (char*str)
{
cout<< "default construct test"<< endl;
int len = strlen(str) + 1;
str_ = new char[len];
memset(str_,0,len);
strcpy(str_,str);
}
void String::display ()
{
cout<< str_ << endl;
}
String& String::operator=(const String& other)
{
if(this ==&other)
{
return *this;
}
int len = strlen(other.str_ ) + 1;
delete [] str_;
str_ = new char[len];
memset(str_,0,len);
strcpy(str_,other.str_);
}
#ifndef _STRINGTOOL_H_
#define _STRINGTOOL_H_
class String;
class StringTool
{
public:
void myStrcat(String &s1,String &s2);
};
#endif
#include "Stringtool.h"
#include "String.h"
#include <string.h>
void StringTool::myStrcat(String &s1,String &s2)
{
strcat(s1.str_,s2.str_);
}
#include "String.h"
int main()
{
StringToolst;
String s1("hello");
String s2(" world");
st.myStrcat(s1,s2);
s1.display();
return 0;
}