C 超载 运算符,因此您可以在该类中添加不同的类并获得第三类

C++ overload the + operator of a class so you can add a different class to that class and get a third class

本文关键字:添加 三类 运算符 超载      更新时间:2023-10-16

所以我只是在玩耍,但是我想看看是否可以超载班级的 运算符,以允许它不将其添加在一起,但将其添加到一个二等级别并因此获得了第三类。

示例:

#include <iostream>
#include <string>
using namespace std;
class dog;
class cat;
class catdog;
class dog
{
    public:
    string name;
    int weight;
    string soundMakes;
    dog(string, int, string);
    catdog operator + (const cat&);
};
dog::dog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}
catdog dog::operator + (const cat& inCat)
{
    catdog newBorn("Rottens", this -> weight + inCat.weight, "Wooeow");
    return newBorn;
}
class cat
{
public:
    string name;
    int weight;
    string soundMakes;
    cat(string, int, string);
};
cat::cat(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}
class catdog
{
    string name;
    int weight;
    string soundMakes;
    catdog(string, int, string);
};
catdog::catdog(string inName, int inWeight, string inSound)
{
    name = inName;
    weight = inWeight;
    soundMakes = inSound;
}
int main()
{
    dog rover("Rover", 20, "Woof");
    cat mittens("Mittens", 10, "Meow");
    catdog rottens = rover + mittens;
    cout << "I have a cat dog, his name is " << rottens.name << " and he weighs " << rottens.weight << endl;
}

我一直在尝试此操作,但是我一直在遇到问题,因为它不知道狗操作员 超载猫是什么(反之亦然,取决于订单)。确切的错误是类是ImComplete。

无论如何是否可以完成我要做的事情?我意识到这个例子似乎很愚蠢,但是如果可以做概念,我会更加努力。

您可以改用非会员operator+。在所有三个类之后放置它,以便可以将它们全部视为完整的类型。

catdog operator + (const dog& inDog, const cat& inCat)
{
    catdog newBorn("Rottens", inDog.weight + inCat.weight, "Wooeow");
    return newBorn;
}

完整的代码和演示:

  • https://godbolt.org/g/1yoq9d
  • http://coliru.stacked-crooked.com/a/a6bc0182103fe414