虚拟运算符重载 C++

Kar*_* O. 4 c++ oop inheritance operator-overloading

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

我的标题是什么样的:

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;
}
Run Code Online (Sandbox Code Playgroud)

ato*_*bol 7

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

         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
Run Code Online (Sandbox Code Playgroud)

如果从 A 派生的类 B 没有重写 A 中声明的方法,则virtual T foo() = 0类 B 是抽象类。

另请参阅以下术语:

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


Som*_*ude 6

如果要覆盖子类中的虚函数,则需要在子类中声明函数覆盖。

所以是的,需要声明。


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