C++自学:friend class友元类

在EquilateralTriangle这个类中,设定一个friend class友元类Homework,使我们能在Homework这个类中访问EquilateralTriangle这个类中的private成员。

// Friend Class

#include 
#include 
using namespace std;

class EquilateralTriangle{
private:
    float a;
    float circumference;
    float area;

public:
    void setA(float length){
        a = length;
        circumference = a*3;
        area = (1.73 * a * a) / 4;
    }

    friend class Homework;
};

class Homework{
public:
    void PrintResults(EquilateralTriangle et){
        cout << "circumference = " << et.circumference << endl;
        cout << "area = " << et.area << endl;
    }
};

int main(){
    EquilateralTriangle et;
    et.setA(3);

    Homework h;
    h.PrintResults(et);
    
    system("pause");
    return 0;
}

你可能感兴趣的:(c++学习,c++,开发语言,算法)