虚拟运算符重载 C++ [英] virtual operator overloading c++

查看:65
本文介绍了虚拟运算符重载 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想为派生类重载=="运算符,我是否需要重写派生类头文件中的重载,或者有没有办法在 .cpp 文件中实现运算符重载而不必在头文件中添加任何内容?如果是这样,派生运算符在 .cpp 中的实现会是什么样子?

Suppose I wanted to overload the "==" operator for a derived class, do I need to rewrite the overload in the derived class header file or is there a way to implement the operator overload in the .cpp file without having to add anything in the header file? And if so, how would the implementation of the derived operator look like in the .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;
}

推荐答案

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

If you want to override a virtual function in a child-class, then you need to declare the function override in the child class.

所以是的,需要声明.

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

Think about it this way: The class declaration could be used in many places and many source files, how else would the compiler know that the function has been overridden?

这篇关于虚拟运算符重载 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆