gpt4 book ai didi

c++ - 在派生类中使用复制赋值

转载 作者:行者123 更新时间:2023-12-01 14:47:29 25 4
gpt4 key购买 nike

cppreference says :

Because the copy assignment operator is always declared for any class, the base class assignment operator is always hidden. If a using-declaration is used to bring in the assignment operator from the base class, and its argument type could be the same as the argument type of the implicit assignment operator of the derived class, the using-declaration is also hidden by the implicit declaration.


根据我的理解,以下代码不应该编译。因为
  • B::operator=(const B&) 是隐式声明的。
  • A::operator=(const A&) 和 using-declaration 都是隐藏的。
  • #include <iostream>
    using namespace std;

    class A {
    public:
    A& operator=(const A& A) {
    cout << "A::opreator=" << endl;
    }
    };

    class B : A {
    public:
    using A::operator=;
    };

    int main() {
    A a1;
    B b1;
    b1 = a1;
    }
    但是,它编译成功并打印“A::operator=”,为什么?

    最佳答案

    来自 C++11 Standards #12.8【强调】:

    24 Because a copy/move assignment operator is implicitly declared for a class if not declared by the user, a base class copy/move assignment operator is always hidden by the corresponding assignment operator of a derived class (13.5.3). A using-declaration(7.3.3) that brings in from a base class an assignment operator with a parameter type that could be that of a copy/move assignment operator for the derived class is not considered an explicit declaration of such an operator and does not suppress the implicit declaration of the derived class operator; the operator introduced by the using-declaration is hidden by the implicitly-declared operator in the derived class.

    class B的隐式声明赋值操作将是这样的:
    B& B::operator=(const B&)
    B中使用声明赋值运算符的参数类型与隐式声明的赋值运算符不同。因此,它禁止派生类的隐式声明 B运算符(operator)。
    为了理解 1 & 2 w.r.t.到您发布的代码:
  • 不,赋值运算符的隐式声明在类 B 中被抑制.
  • 不,它们不会被隐藏。
  • 关于c++ - 在派生类中使用复制赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62525799/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com