C ++重载<<运算符

我正在尝试重载c ++中的<<操作符,我已经正确实现了代码,但是我对重载概念的整体工作方式有一些疑问。

  1. 为什么需要传递operator <<函数中的ostream对象
  2. 引用?
  3. 为什么不能将函数的返回类型设为'std :: ostream'而不是
  4. 'std :: ostream&'吗?
  5. 是ostream类的属性,需要
  6. 'operator <<'函数返回一个内存地址或执行所有
  7. 运算符重载需要通过引用传递并返回
  8. 类型也应该作为参考?

这是代码。

    #include<iostream>
    enum MealType{NO_PREF,REGULAR,LOW_FAT,VEGETARIAN};

    struct Passenger{
            char name[30];
            MealType mealPref;
            bool freqFlyer;
            int passengerNo;
    };

    //Overloading the << operator

    std::ostream& operator<<(std::ostream& out,const Passenger& pass){
            out<<pass.name<<" "<<pass.mealPref;
            if(pass.freqFlyer){
                    out<<" "<<"Passenger is a freqent flyer ";
            }
            else{
                    out<<" "<<"Passenger is not a frequent flyer ";
            }
            return out;
    }

int main(){
        Passenger p1 = {"Jacob",LOW_FAT,false,2342};
        std::cout<<p1;
        return 0;
}

编辑1: 为什么我必须在重载函数定义中使用<<操作符。它的功能像按位移位还是类似std :: cout <<“”中的<<?

评论
det
det

Not all operator overloading requires passing by reference. For example if you write a class which encapsulates a 2D point and you make an operator- for two of these, you'd probably take the arguments by value (since they are small and simple types with "value semantics"), and it would return the distance by value (because there's presumably no preallocated distance object which could be returned, you are creating a new one). That is:

dist2d operator-(point2d a, point2d b) {
    return {a.x - b.x, a.y - b.y};
}

std::ostream is not copyable, because what would it mean to copy a stream (which does not contain its own history)? So you have to pass it by reference or pointer always.

点赞
评论