zoukankan      html  css  js  c++  java
  • How to use base class's assignment operator in C++

    看了android下的代码,好长时间没看了,有个关于C++的知识点不是很清楚,查了下:

    如何使用基类中的赋值运算符?

    引述自http://stackoverflow.com/questions/1226634/how-to-use-base-classs-constructors-and-assignment-operator-in-c

    参考:《C++ Primer》4ed_CN  p_495

    编译器的默认设置:

    struct base
    {
       base() { std::cout << "base()" << std::endl; }
       base( base const & ) { std::cout << "base(base const &)" << std::endl; }
       base& operator=( base const & ) { std::cout << "base::=" << std::endl; }
    };
    struct derived : public base
    {
       // compiler will generate:
       // derived() : base() {}
       // derived( derived const & d ) : base( d ) {}
       // derived& operator=( derived const & rhs ) {
       //    base::operator=( rhs );
       //    return *this;
       // }
    };
    int main()
    {
       derived d1;      // will printout base()
       derived d2 = d1; // will printout base(base const &)
       d2 = d1;         // will printout base::=
    }

    如果我们在派生类中自己定义了拷贝构造函数、"="重载运算符,那么我们就需要显示的调用基类中的拷贝构造函数和基类中的“=”重载运算符。

    class Base
    {
        /* .. */
    };
    
    class Derive: public Base
    {
        //如果没有显式调用Base(d),则调用Base中的无参的Base拷贝构造函数
        Derived(const Derived &d): Base(d) 
        {
            /* ... */
        }
    
        Derived &Derived::operator=(const Derived &rhs)
        {
            if(this != &rhs)
            {       
                Base::operator=(rhs);
                /* ... */
            }       
    
            return *this;
        }
    };
  • 相关阅读:
    EasyUI问题小结(不定期更新·······)
    windows服务与前台交互
    C#捕获Windows窗体控件
    C#操作AD域中计算机
    远程桌面 Rdp文件的生成
    正则匹配的例子
    Nodejs中npm install 命令的问题
    Windows下使用curl命令
    关于PostmanURL中不能传递中文的问题
    MyBatis_Study_004(动态代理)
  • 原文地址:https://www.cnblogs.com/openix/p/3251293.html
Copyright © 2011-2022 走看看