【问题标题】:how to implement a operator use in hierarchy?如何在层次结构中实现运算符使用?
【发布时间】:2019-02-16 20:02:51
【问题描述】:

我有一个带有几个派生类的Base 类:

class Base {
private:
    long id;
public:
    Base() {}
    ~Base() {}
    Base &operator = (long temp) {
        id = temp;
        return *this;
    }
};

template <class C>
class Temp1 : public Base {
public:
    Temp1() {}
    ~Temp1() {}
    //do something;
};

template <class C>
class Temp2 : public Base {
public:
    Temp2() {}
    ~ Temp2() {}
    //do something;
};

class Executor1 : public Temp1<int> {
public:
    Executor1() {}
    ~Executor1() {}
};

class Executor2 : public Temp2<char> {
public:
    Executor2() {}
    ~Executor2() {}
};

我希望这些类支持operator =
例如:

int main()
{
    long id1 = 0x00001111, id2 = 0x00002222;
    Executor1 exec1;
    Executor2 exec2;

    exec1 = id1;  //exec2.id = id1;
    exec2 = id2;  //exec2.id = id2;
}

我在Base 中定义operator =,其声明为Base &amp;operator = (long);

但是很明显有一个问题是= 不能派生类。所以我必须定义operator = 对每个Executor 做同样的事情。

如何更好地处理Base中的这种情况?

【问题讨论】:

  • 我建议不要定义采用不相关类型的operator=
  • 更好。尽管所有那些丢失的分号也是我所说的事情之一。不过我自己为你修好了。
  • 写一个函数from_int或者定义一个显式构造函数。 operator= 就像你想定义的那样非常令人困惑,需要一些严肃的理由。
  • 不相关,但没有任何虚函数的层次结构非常可疑。

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


【解决方案1】:

您必须将 =-operator 拉到类的范围内:

class Base
{
public:
    long id;

    Base& operator=(long id)
    {
        this->id = id;
        return *this;
    }
};

class Temp2
    : public Base
{
public:
    using Base::operator=;
};

您必须将 operator= 拉入作用域,因为 Temp2 的隐式生成的复制 operator= 隐藏了 Base 的 operator=。从@Angew 的评论中得到这个提示。

【讨论】:

  • 我试过了。但是程序 Segmentation fault (core dumped) 在我运行它时
  • @umbreLLaJYL - 分段错误是由于您的程序中的错误。在你没有在这里显示的代码中。这回答了您提出的问题。如果您对 seg 错误有新的不相关问题,可以使用另一个 minimal reproducible example 发布另一个问题。
  • @umbreLLaJYL 它似乎工作正常,您可能会针对这个特定问题提出另一个问题。当你写这个新问题时,请直接提供minimal reproducible example
  • @StoryTeller 我的意思是程序运行良好。添加该行后它崩溃了。
  • @JulianH 不,绝对不是在调用复制 ctor。只是该类有隐式定义的operator=,它隐藏了继承的operator=。这就是为什么必须将其纳入范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 1970-01-01
  • 2012-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多