友元函数
#include <iostream>
using namespace std;
//友元函数定义在类外部,有权访问类的所有私有和保护成员
// 友元函数不是成员函数
class Box{
public:
double length;
friend void printWidth(Box box);
void setWidth(double width);
private:
double width;
};
void Box::setWidth(double width) {
this->width = width;
}
void printWidth(Box box){
cout<<"width of box:"<<box.width<<endl;
}
int main(){
Box box;
box.setWidth(2);
printWidth(box);
return 0;
};
- 友元函数需要访问
#include <iostream>
using namespace std;
//友元函数定义在类外部,有权访问类的所有私有和保护成员
// 友元函数不是成员函数
class Box{
public:
double length=0;
friend void printWidth(Box box);
void setWidth(double width);
private:
double width;
};
void Box::setWidth(double width) {
this->width = width;
}
void printWidth(Box box){
cout<<"test"<<endl;
cout<<"height of box:"<<box.length<<endl;
cout<<"width of box:"<<box.width<<endl;
}
int main(){
Box box;
box.setWidth(2);
printWidth(box);
return 0;
};
// 友元类
#include <iostream>
using namespace std;
//友元函数定义在类外部,有权访问类的所有私有和保护成员
// 友元函数不是成员函数
class Box{
public:
double length=0;
friend class BigBox;
void setWidth(double width);
Box()
{
cout<<"普通构造函数"<<endl;
this->setWidth(2);
}
Box(const Box &box){
cout<<"复制构造函数"<<endl;
this->width = box.width;
}
private:
double width;
};
void Box::setWidth(double width) {
this->width = width;
}
class BigBox{
public:
int length;
double width;
double height;
void Print(Box box)
{
box.setWidth(2);
cout<<"the box's width is "<<box.width<<endl;
}
};
int main(){
BigBox bigbox;
Box box;
box.setWidth(2);
bigbox.Print(box);
return 0;
};