班级的朋友

时间:2012-11-21 14:05:40

标签: c++ visual-c++

我有2个课程:Budget和AuxiliaryOffice,我正在使用朋友的功能:朋友AuxiliaryOffice :: addBudget(double,Budget&);访问Budget的私人成员corpDivision。

auxil.h

#ifndef AUXIL_H
#define AUXIL_H
class Budget;
class AuxiliaryOffice
{
private:
    double auxBudget;
public:
    AuxiliaryOffice(){auxBudget=0.0;}
    double getDivisionBudget()const{return auxBudget;}
    void addBudget(double b, Budget &);
};
#endif

budget.h

#include"auxil.h"
#ifndef BUDGET_H
#define BUDGET_H
class Budget
{
private:
    static double corpDivision;
    double divisionBudget;
public:
    Budget(){divisionBudget=0.0;}
    void addBudget(double b){divisionBudget+=b; corpBudget+=b;}
    double getDivisionBudget()const{return divisioBudget;}
    double getCorpDivision()const{return corpDivision;}
    friend AuxiliaryOffice::addBudget(double,Budget &);
};
#endif

auxil.cpp

#include"auxil.h"
#include"budget.h"

void AuxiliaryOffice::addBudget(double b, Budget& div)
{
    auxBudget+=b;
    **div.corpDivision+=b;** //this line it is the problem. 
}

div.corpDivision + = b - >预算:: corpDivision无法访问

1 个答案:

答案 0 :(得分:0)

经过一些尝试,它可以工作,但我必须纠正你的样本中的一些问题:

class Budget;
class AuxiliaryOffice
{
private:
    double auxBudget;
public:
    // It would be a good idea to add spaces to your code to help other reading it
    AuxiliaryOffice() { auxBudget = 0.0; }
    double getDivisionBudget() const { return auxBudget; }
    void addBudget(double b, Budget &);
}; // so far, so good    

class Budget
{
private:
    static double corpDivision;
    double divisionBudget;
    double corpBudget; // ** this was missing **

public:
    Budget() { divisionBudget = 0.0; }
    void addBudget(double b) { divisionBudget += b; corpBudget+=b; }
    double getDivisionBudget() const { return divisionBudget; }
    double getCorpDivision() const { return corpDivision; }

    // ** note the "void" here, missing from your sample
    friend void AuxiliaryOffice::addBudget(double, Budget&);
};

// this is also required to compile properly, usually in a Budget.cpp file
double Budget::corpDivision;