【问题标题】:Bring to derived object the assignment operator from base (prior to C++11)将赋值运算符从基类引入派生对象(C++11 之前)
【发布时间】:2022-06-22 23:37:01
【问题描述】:

我有一个类似这样的代码:

template <typename T>
struct B
{
    B &operator =(const T &) { return *this; }
};

struct D : B<int> {};

int main()
{
    D d;
    d = 0;

    return 0;
}

失败的:

error: no viable overloaded '='
   d = 0;
   ~ ^ ~
note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const D' for 1st argument
struct D : B<int> {};
       ^
note: candidate function (the implicit move assignment operator) not viable: no known conversion from 'int' to 'D' for 1st argument
struct D : B<int> {};
       ^

这个错误很容易发现和理解:D 缺少与int 的赋值运算符,即使它的基类有它。从 开始,我们可以解决这个问题,将赋值运算符从基础对象“提升”到派生对象:

struct D : B<int> { using B::operator =; /* Easy fix! */ };

但我正在处理一个 项目,因此此修复程序不可用。在 C++11 之前这是如何解决的?

【问题讨论】:

  • 听起来很奇怪。 using 侦探来自早期的 C++。你在 C++98 中遇到什么错误?也许using B&lt;int&gt;::operator =; 会起作用。
  • 对于 C++98,using B&lt;int&gt;::operator=; 为我工作。
  • 在此上下文中使用using 指令是C++11 feature

标签: c++11 c++98 c++ inheritance operator-overloading c++98


【解决方案1】:

但我正在开发一个 c++98 项目,因此此修复程序不可用。在 C++11 之前这是如何解决的?

D 中定义一个operator= 调用B::operator=

struct D : B<int> {
    D& operator=(const int &rhs) {
        B<int>::operator=(rhs);
        return *this;
    }
};

【讨论】:

  • 嘿 - 你比我快了大约 30 秒。但是,D::operator= 的代码非常好,也许我们应该把它发布两次。 :-)
【解决方案2】:

您可以将所需的运算符函数添加到派生类中,并从中调用相应的基类运算符:

template <typename T>
struct B {
    B& operator = (const T&) { return *this; }
};

struct D : B<int> {
    D& operator = (const int& rhs) {
        B<int>::operator = (rhs);
        return *this;
    }
};

int main()
{
    D d;
    d = 0;

    return 0;
}

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 2016-07-10
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2012-04-21
    • 2012-06-05
    相关资源
    最近更新 更多