重写C++中的非void函数,supers返回值返回到哪里?

发布于 2024-11-09 10:08:41 字数 1694 浏览 0 评论 0原文

我正在编写一个具有三个继承级别的程序。要求我在基类中重载operator==,然后在派生类中重写该函数(我不允许更改此设计)。

该函数是一个 bool,它对两个对象进行成员比较。如何处理super返回值?在 Java 中获取这个值很简单:我只需将重写函数的第一行调用 super,例如:

retValue = super.myFunction();

我需要实现相同的结果,但在 C++ 中并且具有可怕的运算符重载。一些重载函数的伪代码将不胜感激。

我还有一个与此相关的问题;如果该运算符用于来自不同子类的实例,会发生什么情况?例如sub1和sub2继承自base,Main中的以下代码行将执行哪个版本的函数:

if (sub1 == sub2)

会产生编译错误吗?

编辑:首先,我是一名学生,所以我无法按照我想要的方式编写代码来完成这项任务。计划要求规定;

“车辆运算符重载: == 运算符

Vehicle 类需要重写 == 运算符。如果两个对象的所有数据字段都相等且乘客列表相同,则两个对象相等。这需要在基类中定义,并且然后在派生类中重写。”

我实际上没有任何代码要发布,因为在阅读比利的回复时,我意识到我实际上已经编写了脱离类的operator==函数(这不允许我覆盖它,并且不满足程序要求)。

例子;

if (sub1 == sub2)

完全是假设的。我实际上将有一个 Vehicle 对象数组,我有一个从 Vehicle 继承的 Car 和 Airplane 类,然后是一个从 Car 继承的 MagicSchoolBus 和一个从 Airplane 继承的 Xwing。在 Vehicle 类中,我有一个 int 'vType_',它标识每个 Vehicle 实例所属的特定子类。为了防止运行时崩溃,我将简单地检查以确保对象在使用 == 运算符之前具有相同的 vType_。

尽管我更愿意编写比较函数,但我不被允许这样做。我必须找到一种方法来使用基类中operator==函数的返回值,因为它正在比较多个数据成员,如果我在每个派生类中重写此代码,我的评分当然会降低。

如果我不能使用该返回值,我要么必须重写代码,要么当对象在基类成员中具有不同的值但在派生类中具有相同的值时,我将得到错误的结果。

我将不得不重写这个函数作为 Vehicle 类的成员,但无论如何我都会发布它,希望它可能有用。 每个派生类都有一些特定于这些车辆类型的成员,以及将进行比较的 Passenger 对象数组。

// 重载相等运算符以进行成员比较

bool 运算符== (Vehicle& obj1, Vehicle& obj2) { 布尔 retValue = false;

if (strcmp(obj1.getName(), obj2.getName()) == 0)
{
    if (obj1.getType() == obj2.getType() && obj1.getFuel() == obj2.getFuel())
    {
        if (obj1.getRate() == obj2.getRate() && obj1.getStatus() == obj2.getStatus())
        {
            retValue = true;
        }
    }
}

return retValue;

}

I'm writing a program with three levels of inheritance. It is required that I overload the operator== in the base class, and then override that function in the derived classes (I am not allowed to change this design).

The function is a bool which does a memberwise comparison of two objects. How do I process supers return value? In Java getting this value is simple: I just make the first line of the overriden function a call to super, for example:

retValue = super.myFunction();

I need to achieve this same result, but in C++ and with awful operator overloading. Some pseudo code for the overrloaded function would be much appreciated.

I also have another question relating to this; What will happen if the operator is used on instances from different subclasses? For example sub1 and sub2 inherit from base, which version of the function will be executed for the following line of code in Main:

if (sub1 == sub2)

Will it generate a compiler error?

Edit: Firstly, I am a student so I cannot write the code to accomplish this task in the way I would like to. The program requirements state;

"Vehicle operator overload: the == operator

The Vehicle class needs to override the == operator. Two objects are equal if all of their data fields are equal and if their passenger lists are identical. This needs to be defined in the base class and then overridden in the derived classes."

I don't really have any code to post because in reading Billy's response I realized that I had actually written the operator== function free of the class (which won't allow me to override it, and won't meet the program requirements).

The example;

if (sub1 == sub2)

was entirely hypothetical. I will actually have an array of Vehicle objects, I have a Car and Airplane class which inherit from Vehicle, and then a MagicSchoolBus which inherits from Car and an Xwing which inherits from Airplane. In the Vehicle class I have an int 'vType_' which identifies the specific subclass each Vehicle instance belongs to. To prevent a runtime crash I will simply check to make sure the objects have the same vType_ prior to using the == operator on them.

As much as I would to prefer to write a compare function, I am not allowed to. I have to find a way to use the return value from the operator== function in the base class because it is comparing several data members, and I will of course be graded down if I rewrite this code in each of the derived classes.

If I can't use that return value I either have to rewrite code, or I will get the wrong result when an object has different values in members of the base class but the same values in the derived class.

I'm going to have to rewrite this function as a member of the Vehicle class but I will post it anyways in hope that it may be useful.
Each of the derived classes have a few more members specific to those types of vehicles, and an array of Passenger objects which will have be compared.

// equality operator overloaded to do a memberwise comparison

bool operator== (Vehicle& obj1, Vehicle& obj2)
{
bool retValue = false;

if (strcmp(obj1.getName(), obj2.getName()) == 0)
{
    if (obj1.getType() == obj2.getType() && obj1.getFuel() == obj2.getFuel())
    {
        if (obj1.getRate() == obj2.getRate() && obj1.getStatus() == obj2.getStatus())
        {
            retValue = true;
        }
    }
}

return retValue;

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心清如水 2024-11-16 10:08:41

因为 C++ 与 Java 不同,支持多重继承,所以您需要通过 SUPER::operator==() 显式指定需要使用哪个 super(将 SUPER 替换为真正的超类名称..)

because C++, unlike Java, supports multiple inheritence, you will need to explicitly specify which super you need to use by SUPER::operator==() (replace SUPER by the real super class name..)

情话难免假 2024-11-16 10:08:41

需要在基类中重载 == 运算符,然后在派生类中重写该函数

这似乎是一件非常奇怪的事情。如果可能的话,运算符重载通常应该是自由函数,而不是类成员。您能否发布一些代码来更具体地描述您想要做什么?因为你想要的一般实现是不可能的。例如,如果您通过基类指针比较 Derived 1 和 Derived 2,编译器如何知道要调用哪个operator==? Derived 1 和 Derived 2 都实现了该功能,但没有办法选择。派生类应该只实现 == 隐藏 基类的实现,在少数情况下,有人可能需要做类似的事情。

不要将运算符重载与虚函数混合在一起——这很痛苦,而且这也不是运算符重载的设计目的。

如何处理 super 返回值?

你不知道。 C++ 中不存在“超级”之类的东西(一方面,如果您从两个类继承,那么语言应该如何知道基本版本是什么?:P)。如果要调用基类的重载,则直接调用基类函数。示例:

class SomeBaseName
{
    int aMember;
public:
    bool operator==(const SomeBaseName& rhs)
    {
        return aMember == rhs.aMember;
    };
};

class Derived : public SomeBaseName
{
    int anotherMember;
public:
    bool operator==(const Derived& rhs) //Note that this is not a virtual function, it is *hidden* instead.
    {
        if (!(SomeBaseName::operator==(rhs))
            return false;
        return anotherMember == rhs.anotherMember;
    }
};

我真的建议你不要这样做……通过运算符重载来这样做是没有意义的。

如果该运算符用于来自不同子类的实例,会发生什么情况?例如sub1和sub2继承自base,Main中的以下代码行将执行哪个版本的函数

两者都不会被调用。该调用不明确,会导致编译时错误。

最后,最后一条建议:不要试图用 Java 来学习 C++。将 C++ 作为一门新语言来学习。它们是不同的语言——比它们相似的语法所暗示的还要多。 C++ 允许您做一些 Java 中完全没有等效项的事情(例如指针算术、运算符重载、多重继承、模板元编程等),并且虽然有一些事情是相似的在某些地方,两种语言的惯用例子彼此非常不同。如果您将某些地方视为 Java 的等价物,那么当语言不同或 C++ 将概念堆积到其(非常不同的)对象模型上时,您就会感到困惑。

It is required that I overload the == operator in the base class, and then override that function in the derived classes

That seems like an extremely strange thing to do. Operator overloads should generally be free functions, not class members, where possible. Could you post some code describing what you want to do more specifically? Because a general implementation of what you'd want is not possible. E.g. if you compare Derived 1 and Derived 2 through a base class pointer, how would the compiler know which operator== to call? Both Derived 1 and Derived 2 implement that function, but there'd be no way to choose. The derived classes should just implement == hiding the implementation of the base class, in the few cases where someone might need to do something like that.

Don't mix operator overloading with virtual functions -- it's painful and it's not how operator overloading is designed to operate.

How do I process supers return value?

You don't. There's no such thing as a "super" in C++ (for one thing, if you inherit from two classes, how is the language supposed to know what the base version is? :P). If you want to call the overload of the base class, you call the base class function directly. Example:

class SomeBaseName
{
    int aMember;
public:
    bool operator==(const SomeBaseName& rhs)
    {
        return aMember == rhs.aMember;
    };
};

class Derived : public SomeBaseName
{
    int anotherMember;
public:
    bool operator==(const Derived& rhs) //Note that this is not a virtual function, it is *hidden* instead.
    {
        if (!(SomeBaseName::operator==(rhs))
            return false;
        return anotherMember == rhs.anotherMember;
    }
};

I really really recommend you not do that though.. it makes no sense to do things that way with operator overloading.

What will happen if the operator is used on instances from different subclasses? For example sub1 and sub2 inherit from base, which version of the function will be executed for the following line of code in Main

Neither will be called. The call is ambiguous and will cause a compile-time error.

Finally, one last piece of advice: Don't try to learn C++ in terms of Java. Learn C++ as a new language. They are different languages -- moreso than their similar syntax would suggest. C++ allows you do do several things for which there is absolutely no equivalent in Java (e.g. pointer arithmetic, operator overloading, multiple inheritance, template metaprogramming, etc.), and while there are some things that are similar in places, idiomatic examples in both languages are very different from each other. If you think of things as the Java equivalents in places you are going to be confused when the languages differ or when C++ piles concepts onto it's (very dissimilar) object model.

梨涡少年 2024-11-16 10:08:41

如果从类继承,则必须使用显式限定符。没有关键字。

class A {
public:
    virtual bool operator==(const A&);
};
class B : public A {
public:
    virtual bool operator==(const B& other) {
        bool result = A::operator==(other);
        //.. do other stuff
    }
};

如果您没有定义新的,则调用基础的。

If you inherit from a class, then you have to use an explicit qualifier. There's no keyword.

class A {
public:
    virtual bool operator==(const A&);
};
class B : public A {
public:
    virtual bool operator==(const B& other) {
        bool result = A::operator==(other);
        //.. do other stuff
    }
};

If you don't define a new one, then the base one is called.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文