• C++程序设计方法2:基本语法2


    对象赋值-赋值运算符重载

    赋值运算符函数是在类中定义的特殊的成员函数

    典型的实现方式:

    ClassName& operator=(const ClassName &right)
    {
        if (this != &right)
        {
          //将right的内容复制给当前的对象
    }
    return *this; }
    #include <iostream>
    using namespace std;
    
    class Test
    {
        int id;
    public:
        Test(int i) :id(i) { cout << "obj_" << id << "created
    "; }
        Test& operator= (const Test& right)
        {
            if (this == &right)
                cout << "same obj!" << endl;
            else
            {
                cout << "obj_" << id << "=obj_" << right.id << endl;
                this->id = right.id;
            }
            return *this;
        }
    };
    
    int main()
    {
        Test a(1), b(2);
        cout << "a = a:";
        a = a;
        cout << "a = b:";
        a = b;
        return 0;
    }

    流运算符重载函数的声明

    istream& operator>>(istream& in, Test& dst);

    ostream& operator<<(ostream& out, const Test& src);

    备注:

    函数名为:
      operaotor>>和operator<<

    返回值为:
      istream& 和ostream&,均为引用

    参数分别:流对象的引用,目标对象的引用。对于输出流,目标对象还是常量

    #include <iostream>
    using namespace std;
    
    class Test
    {
        int id;
    public:
        Test(int i) :id(i)
        {
            cout << "obj_" << id << "created
    ";
        }
        friend istream& operator >> (istream& in, Test& dst);
        friend ostream& operator << (ostream& out, const Test& src);
    };
    //备注:以下两个流运算符重载函数可以直接访问私有成员,原因是其被声明成了友元函数
    istream& operator >> (istream& in, Test& dst)
    {
        in >> dst.id;
        return in;
    }
    
    ostream& operator << (ostream& out, const Test& src)
    {
        out << src.id << endl;
        return out;
    }
    
    int main()
    {
        Test obj(1);
        cout << obj;
        cin >> obj;
        cout << obj;
    }
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    百度地图代码API
    3层下拉列表
    stl+数论——1247D
    数论+乱搞——cf181B
    思维+multiset优化——cf1249E
    线性基思想+贪心——cf1249C
    tarjan求强连通+缩点——cf1248E
    排序+模拟+优先队列——cf1248E
    栈+括号序列+暴力枚举——cf1248D1
    二分+贪心——cf1251D
  • 原文地址:https://www.cnblogs.com/hujianglang/p/6623999.html
Copyright © 2020-2023  润新知