第五节 · 偷懒的诀窍 · 合成函数与虚析构
class Box
{
private:
double width;
public:
Box(double w) : width(w) {}
// 友元函数:可以访问私有成员
friend void printWidth(const Box& b);
// 友元类:整个类都可以访问
friend class BoxFactory;
};
void printWidth(const Box& b)
{
cout << "Width: " << b.width << endl; // OK:友元可以访问
}
class BoxFactory
{
public:
static Box createBox(double w)
{
Box b(w);
b.width *= 2; // OK:友元类可以访问
return b;
}
};习题
Last updated