C++子类操作符重载

 

#include<iostream>
#include<string>

class Base { 
public:
    Base(const std::string& name,int age):m_name(name),m_age(age) { }
    //输出操作符重载
    friend std::ostream& operator<<(std::ostream& os, const Base& h) {  //基类操作符重载
        os << h.m_name << "," << h.m_age ;
        return os;
    }
    
private:
    std::string m_name;
    int m_age;
  
 };

class Derived :public Base {
public:
    Derived(const std::string& name, int age,int no):Base(name,age),m_no(no){}
    
    //子类操作符重载
    friend std::ostream& operator<<(std::ostream& os, const Derived& t) {  
        os << (Base&)t << ',' << t.m_no ;
        //(Base&)t   调用基类的重载函数
        return os;
    }

private:
    int m_no;
 };

int main()
{
    Derived d("李明", 52,10010);
        
    std::cout << d << std::endl;
    return 0;
}

 

 

 

posted @ 2020-08-30 12:40  天子骄龙  阅读(443)  评论(0编辑  收藏  举报