C++比较抽象类的后代

标签 c++ abstract-class abstract overriding virtual-functions

<分区>

是的,我知道比较抽象类的不同后代是不好的语气。但我真的必须这样做。

我有这个简单的抽象类:

class Figure {
    public:
    virtual double Square() = 0;
    virtual ~Figure() {};
}

我想添加的是这样的:

bool operator<(const Figure& other) {};

它将比较其后代 - 几何图形,即 Triangle、Rectangle、Octagon - 使用方法 Square() 中返回的面积。

这有可能吗?

最佳答案

来自您的评论 return (*this->Square() < other->Square());您的问题似乎只是基本语法。

this是一个简单的指针。所以典型的正确语法就是 this->Square() .当然,因为它在成员函数中,所以 this可以完全省略,就像 Square() .

other是一个引用,因此使用点运算符作为 other.Square()

另一个可能与您的最新评论相关的有用的事情是使 operator< 函数 const因为它没有修改被调用的对象。

所以生成的代码应该更像:

bool operator<(const Figure& other) const
{
    return Square() < other.Square();
}

关于C++比较抽象类的后代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41366303/

相关文章:

c++ - 访问器会影响应用程序的性能吗?

java - 我们可以在抽象类中使用静态方法吗?

java - 静态/抽象冲突

c++ - 如何 std::hash 一个无序的 std::pair

java - winio64.dll 中有哪些方法以及如何使用它们

C++ 指针与数组表示法

java - 派生类可以调用它们的抽象父类的构造函数,调用它们尚未实现的方法吗?

php - php中抽象和接口(interface)有什么区别?

ruby 场 : documenting abstract methods implementations