【问题标题】:friend function + operator overloading [duplicate]友元函数+运算符重载[重复]
【发布时间】:2014-03-09 06:29:30
【问题描述】:

我正在做一个类似于工资单的课程项目。部分提示说

"您可以定义一个重载

我知道友元函数是什么,但我不记得学习过重载

我该如何实际实施呢?这是我到目前为止的代码:

#include <iostream>
#include <string>

using namespace std;

//Base class
class Employee
{
public:
    Employee(string a, string b, string c, string d);
    ~Employee();
    int virtual earnings();
    void virtual print();
protected:
    string first, last, brithday, department;
};

Employee::Employee(string f, string l, string b, string d)
{
    first = f;
    last = l;
    brithday = b;
    department = d; //department code
    cout << "Employee created." << endl;
}

Employee::~Employee(void)
{
    cout << "Employee deleted." << endl;
}

int Employee::earnings()
{
    int earnings = 100; //To be added
    return earnings;
}

void Employee::print()
{
    //IDK 
}

【问题讨论】:

    标签: c++ operator-overloading friend


    【解决方案1】:

    不要让&lt;&lt; 运算符混淆您。归根结底,重载运算符只是另一种命名函数的方式

    如果你有这段代码:

    int i = 1;
    std::string s = "x";
    double d = 0.5;
    std::cout << s << i << d;
    

    那么这只是另一种说法:

    int i = 1;
    std::string s = "x";
    double d = 0.5;
    std::operator<<(std::cout, s).operator<<(i).operator<<(d);
    

    顺便说一句,这使得链接调用更明显有效,因为operator&lt;&lt; 返回了对流本身的引用。请注意,这里涉及到两种不同的operator&lt;&lt;std::string 的一种是带有std::ostream 引用参数的free-standing functionintdouble 的一种是std::ostream member functions .

    有了这些知识,很容易想象一下,我们将只处理通常命名的函数,例如“打印”:

    int i = 1;
    std::string s = "x";
    double d = 0.5;
    print(std::cout, s).print(i).print(d);
    

    事实上,你可以想象没有重载,但是它们都有不同的名字。这使得整个事情更容易理解:

    int i = 1;
    std::string s = "x";
    double d = 0.5;
    printStringOnStream(std::cout, s).printInt(i).printDouble(d);
    

    如果你想为你自己的班级提供std::ostream打印,你所要做的就是像std::string那样做:提供一个独立的operator&lt;&lt;,它需要一个std::ostream引用和一个(const)对您的对象的引用,并返回对流的引用:

    std::ostream &operator<<(std::ostream &stream, Employee const &employee)
    {
        // ...
        return stream;
    
    }
    

    现在// ... 部分是朋友关系发挥作用的地方。为了正确打印Employee,您需要访问其所有私有成员。在不向公众公开的情况下提供此访问权限的最简单方法是将您的 operator&lt;&lt; 声明为 Employee 的朋友:

    class Employee
    {
        // ...
        friend std::ostream &operator<<(std::ostream &stream, Employee const &employee);
    }; 
    
    std::ostream &operator<<(std::ostream &stream, Employee const &employee)
    {
        stream << employee.earnings; // and so on
        return stream;
    }
    

    好了,为您的员工完美打印:

    std::cout << "xyz" << my_employee << "abc" << 0.5 << 1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-19
      • 2017-07-26
      • 1970-01-01
      • 1970-01-01
      • 2016-09-09
      • 2011-08-25
      • 1970-01-01
      • 2016-01-24
      相关资源
      最近更新 更多