虚运算符重载 C++

virtual operator overloading c++

假设我想为派生 class 重载“==”运算符,我是否需要在派生 class header 文件中重写重载或者是否有无需在 header 文件中添加任何内容即可在 .cpp 文件中实现运算符重载的方法?如果是这样,派生运算符的实现在 .cpp 中会是什么样子?

我的 header 长什么样:

class A
{
    public:
    A();
    ~A();
    virtual bool operator==(const A &ref) = 0;
    protected:
    int year;
    string note;
}
class B:A
{
    public:
    B();
    ~B();
    bool operator==(const B &ref); //is this needed or not?
    private:

    int month, day;
}

如果你想在子class中覆盖一个虚函数,那么你需要在子class中声明函数覆盖。

所以是的,需要声明。


这样想:class 声明可以在很多地方和很多源文件中使用,否则编译器怎么知道该函数已被覆盖?

必须在派生的 class 中重新声明函数。否则 1) 派生的 class 也将是抽象的,并且 2) 如果 class 最初未在此 class.[=11= 中声明,则您不能定义它的成员函数]

考虑到函数声明应该如下所示

virtual bool operator==(const A &ref) const = 0;
                                      ^^^^^ 

如之前的回答所述,您必须在派生 class 中定义函数。此外,在覆盖时,应始终使用关键字:override

在你的例子中,

virtual bool operator==(const A &ref) = 0;

未被

覆盖
bool operator==(const B &ref);

即使你定义了后者,class B 仍然是抽象的。如果 B 中的 operator== 声明为

bool operator==(const B &ref) override;

然后编译器会产生一个错误,通知我们这个函数没有覆盖任何东西。

C++ 方法覆盖中的函数签名必须完全匹配(如果 return 类型是指针,则 return 类型除外):

         class A { ... };
         class B : A { ... };
class A: virtual bool operator==(const A &ref) = 0;
class B:         bool operator==(const A &ref) override; // OK
class B:         bool operator==(const B &ref) override; // Invalid

如果从 A 派生的 class B 没有覆盖 A 中声明为 virtual T foo() = 0 的方法,则 class B 是一个抽象 class.

另请参阅以下条款:

  • 协方差(计算机科学)
  • 逆变(计算机科学)