创建友元函数以从两个类访问私有变量

时间:2018-05-24 20:05:53

标签: c++ class friend

问题是通过添加两个类的朋友的函数来访问来自两个不同类的输出的私有变量。

class Salesperson;

class Sale {
private:
    string date;
    double total;
    int SalespersonIdNum;
public:
    Sale(string, double, int);
    friend void display(Sale &, Salesperson &);
};
Sale::Sale(string d, double t, int S) {
    >>d = date;
    >>t = total;
    >>S = SalespersonIdNum;
}
//Salesperson class
class Salesperson {
private:
    int idNum;
    string lastName;
public:
    Salesperson(int, string);
    friend void display(Sale &, Salesperson &);
};
Salesperson::Salesperson(int i, string l) {
    >>i = idNum;
    >>l = lastName;
}

void display(Sale &s, Salesperson &sp) {
    //Output Sale info
    cout << " ID of person who completed sale: " << s.SalespersonIdNum << endl;
    cout << " Sale Total: " << s.total << endl;
    cout << " Sale Date: " << s.date << endl;
    //Output Saleperson info
    cout << " Sales Person ID: " << sp.idNum << endl;
    cout << " Sales Person Last Name: " << sp.lastName << endl << endl;
}

int main() {

    Sale s1("10/06/2008", 78.45, 123);
    Salesperson emp1(123, "Pelletier");

    display(s1, emp1);

    Sale s2("05/21/2010", 162.59, 321);
    Salesperson emp2(321, "Howel");

    display(s2, emp2);

    return 0;
}

理想情况下,显示功能应该能够访问由我的对象定义定义的变量,但是当我去运行并显示它们时,函数会显示它。

ID of person who completed sale: 124                                                    
 Sale Total: 2.07482e-317                                                                
 Sale Date:                                                                              
 Sales Person ID: 6299816                                                                
 Sales Person Last Name:  

 ID of person who completed sale: 1677231376                                             
 Sale Total: 2.07417e-317                                                                
 Sale Date:                                                                              
 Sales Person ID: 1                                                                      
 Sales Person Last Name:                                                                 


...Program finished with exit code 0                                                     
Press ENTER to exit console.

根据我的理解,友元函数应该像那样工作,但也许问题在于构造函数,但我认为这些也是正确完成的。至于输出可能是输出内存地址或其他东西,但我不知道那个

编辑:&gt;&gt;我他妈的被重新启动

1 个答案:

答案 0 :(得分:2)

您的作业在构造函数中的方向错误。

Sale::Sale(string d, double t, int S) {
    d = date;
    t = total;
    S = SalespersonIdNum;
}

他们需要:

Sale::Sale(string d, double t, int S) {
    date = d;
    total = t;
    SalespersonIdNum = S;
}

最好使用列表初始化语法。

Sale::Sale(string d, double t, int S) :
    date(d),
    total(t),
    SalespersonIdNum(S) { }