简体   繁体   English

如何使这个 operator= 重载工作?

[英]How to make this operator= overload work?

I was experimenting with making the operator= be virtual, like so:我正在尝试使operator=成为虚拟的,如下所示:

#include <iostream>
#include <string>

class Base {
public:
    std::string field1;
    Base(std::string str) : field1(str) {}

    virtual Base& operator=(const Base& other)
    {
        field1 = other.field1;
        return *this;
    }
};

class Derived : public Base {
public:
    std::string field2;
    Derived(std::string str1, std::string str2) : Base(str1), field2(str2) {}

    virtual Derived& operator=(const Derived& other) override
    {
        Base::operator=(other);
        field2 = other.field2;
        return *this;
    }
};

However, this gives a compiler error, because the Derived function is not actually overloading anything, the signatures are different.但是,这会产生编译器错误,因为Derived function 实际上并没有重载任何东西,签名不同。

Is it possible to override the operator= to write code like this?是否可以覆盖operator=来编写这样的代码?

Base* ptr = new Derived("old 1", "old 2");
Derived derived("new 1", "new 2");

*ptr = derived; // <- use the derived class operator= to assign both field1 and field2

This operator该运算符

virtual Derived& operator=(const Derived& other);

does not override the copy assignment operator declared in the base class.不会覆盖在基础 class 中声明的复制赋值运算符。

You have to write你必须写

Derived& operator=(const Base& other) override;

That is the type of the parameter shall be const Base & .即参数的类型应为const Base &

Here is a demonstrative program.这是一个演示程序。

#include <iostream>

struct A
{
    virtual A & operator =( const A & )
    {
        std::cout << "A::operator =\n";
        return *this;
    }
};

struct B : A
{
    virtual B & operator =( const A &a ) override
    {
        A::operator =( a );
        std::cout << "B::operator =\n";
        return *this;
    }
};


int main() 
{
    B b1;
    
    A &rb1 = b1;
    
    B b2;
    b2 = rb1;
    
    return 0;
}

Its output is它的 output 是

A::operator =
B::operator =

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM