用同一个类定义两个指针变量,这两个指针变量指向同一段空间,最后释放两次—浅拷贝
指针变量指向不同的空间—深拷贝
友元是一种允许非类成员函数访问类的非公有成员的一种机制。
什么样的函数为友元函数:函数不是类的一部分,但又需要频繁地访问类的数据成员函数不是类的一部分,但又需要频繁地访问类的数据成员
作用:提高程序的运行效率(即减少了类型和安全性检查及调用的时间开销)
可以把一个函数指定为类的友元,也可以把整个类指定为另一个类的友元。
友元:非类成员函数可以访问类的非公有成员(protected、private)
工程应用:提高程序运行效率(省去了函数调用返回等一系列时间)
友元的种类:友元函数,友元类(不传递,不继承,单项),友元成员函数
类前置声明:必须将类的成员函数类外实现
友元函数在类作用域外定义,但它需要在类体中进行说明
格式:
friend 类型 友元函数名(参数表);
#include <iostream>
using namespace std;
class Test;
class A
{
public:
friend class Test;
void print(Test &t);
//void print1(Test &t);
private:
int count;
};
class Test
{
public:
//friend class A;
friend void A::print(Test &t);
// friend void A::print1(Test &a);
Test();
Test(int num);
void setNum(int num);
int getNum();
void print();
void print1(A &a);
friend void func(Test &other); //友元函数
private:
int num;
};
Test::Test()
{
}
Test::Test(int num):num(num)
{
}
void Test::setNum(int num)
{
this->num = num;
}
int Test::getNum()
{
return this->num;
}
void Test::print()
{
cout << "num = " << this->num << endl;
}
void Test::print1(A &a)
{
cout << a.count << endl;
}
void A::print(Test &t)
{
cout << "num = " << t.num << endl;
}
// void A::print1(Test &t1)
// {
// cout << t1.num << endl;
// }
//友元:非类成员函数可以访问类的非公有成员(protected、private)
//工程作用:提高程序运行效率(省去了函数调用返回等一系列时间)
//友元的种类分为:友元函数、友元类(不传递,不继承、单向的)、友元成员函数
void func(Test &other)
{
for (int i = 0; i < 100000; i++)
{
cout << other.num << endl;
//cout << other.getNum() << endl;
}
}
int main()
{
Test t;
t.setNum(5);
cout << t.getNum() << endl;
return 0;
}