c++ - 排序函数,它采用指向接口(interface)类的指针 vector

标签 c++ class inheritance

我最近开始学习 C++(之前没有编程知识)。我用过 Alex Allain 的书“Jumping into c++”,我发现它最有用!然而,我已经读到类、继承和多态性的章节,虽然我确实理解其中的大部分内容,但我还是无法解决这个问题。

书中要求我解决以下问题:

Implement a sort function that takes a vector of pointers to an interface class, Comparable, that defines a method, compare(Comparable& other), and returns 0 if the objects are the same, 1 if the object is greater than other, and -1 if the object is less than other. Create a class that implements this interface, create several instances, and sort them. If you're looking for some inspiration for what to create—try a HighScoreElement class that has a name and a score, and sorts so that the top scores are first, but if two scores are the same, they are sorted next by name.

我已经创建了类 Comparable 和 HighScores:

class Comparable {

public:

    virtual int compare(Comparable& other)=0;

};



class HighScore : public Comparable {

public:
    HighScore(int, std::string);

    virtual int compare(Comparable& other);


private:
    int highscore;
    std::string name;

};

如果我尝试覆盖 HighScore 中的继承函数,我无法比较,例如 int highscore 与 (Comparable& other) 的 int highscore,因为我无法访问 other.highscore。示例如下:

int HighScore::compare(Comparable& other){

    if (highscore == other.highscore) {
        return 0;
    }

    //...
}

我想我也许可以将虚拟方法更改为类似的东西:

int HighScore::compare(HighScore& other){

    if (highscore == other.highscore) {
        return 0;
    }

    //...
}

因为这将允许我访问 other.highscore(我曾希望我能工作,因为 HighScore 也可以被认为是可比较的。但可惜没有这样的运气。我该怎么办,我完全不知道如何继续,如果能得到任何帮助,我将不胜感激。谢谢 :)

最佳答案

事实上,尝试根据两个或多个对象的运行时类型来选择行为在像 C++ 这样的单一调度语言中有点繁琐。

最简单的解决方案是使用 RTTI 来确定其他对象是否具有与我们的类型相当的类型:

int HighScore::compare(Comparable& other){

    int other_highscore = dynamic_cast<HighScore&>(other).highscore;

    if (highscore == other_highscore) {
        return 0;
    }

    //...
}

如果类型不可比较,这将引发异常,这可能是您能做的最好的事情。

或者,您可以实现涉及两个虚函数的双重调度机制(例如“访问者模式”)。我会让你自己研究一下,因为一个例子会很冗长而且不会特别鼓舞人心。

希望您很快就能学会如何使用编译时泛型而不是运行时抽象接口(interface)来实现这一点,后者在 C++ 中更为惯用。如果这本书没有教你这些,就把它扔掉并获得 these 之一。相反。

关于c++ - 排序函数,它采用指向接口(interface)类的指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16176516/

相关文章:

c++ - 有没有一种方法可以使 MainWindow 窗口任务栏图标闪烁?

java - 有没有办法从 .dex 文件中获取所有类的列表?

c++ - 在类外设置 const int 成员变量 (C++)

Java:是否可以说变量类型必须满足多重继承/接口(interface)要求

c++ - 具有非连续存储(即!= vecS)和 add_edge() 的最小 boost adjacency_list

c++ - 查看 STL 容器中的下一个元素

Java指定子类构造函数签名

c++ - 避免使用虚方法构造具有空基类的构造函数

c++ - QBoxLayout 与 QMainWindow 对比 QWidget

c++ - 使用另一个类对象的 std::vector 类