C++ C++;重载+;类的运算符,以便您可以向该类添加其他类并获得第三个类

C++ C++;重载+;类的运算符,以便您可以向该类添加其他类并获得第三个类,c++,C++,所以我只是在玩,但是我想看看我是否可以重载一个类的+操作符,让它不把自己的两个加在一起,而是把它添加到第二个类,得到第三个类 例如: #include <iostream> #include <string> using namespace std; class dog; class cat; class catdog; class dog { public: string name; int weight; string sound

所以我只是在玩,但是我想看看我是否可以重载一个类的+操作符,让它不把自己的两个加在一起,而是把它添加到第二个类,得到第三个类

例如:

#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;
}
#包括
#包括
使用名称空间std;
班犬;
猫类;
猫狗类;
班犬
{
公众:
字符串名;
整数权重;
弦乐;
dog(string、int、string);
猫狗操作员+(常数猫&);
};
dog::dog(名称中的字符串、重量中的字符串、深度中的字符串)
{
name=inName;
重量=英寸重;
soundMakes=内陷;
}
猫狗::操作员+(常数猫和猫)
{
猫鼬新生儿(“腐烂”,这->体重+增加体重,“Woooow”);
返回新生儿;
}
班猫
{
公众:
字符串名;
整数权重;
弦乐;
cat(字符串、整型、字符串);
};
cat::cat(名称中的字符串、重量中的字符串、深度中的字符串)
{
name=inName;
重量=英寸重;
soundMakes=内陷;
}
班猫狗
{
字符串名;
整数权重;
弦乐;
猫狗(字符串、整数、字符串);
};
catdog::catdog(名称中的字符串、权重中的字符串、深度中的字符串)
{
name=inName;
重量=英寸重;
soundMakes=内陷;
}
int main()
{
狗漫游者(“漫游者”,20,“汪汪”);
猫手套(“手套”,10,“喵喵”);
猫狗rottens=漫游者+连指手套;

cout您可以使用非成员的
操作符+
来代替。将它放在所有3个类之后,以便它可以将它们都视为完整类型

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

    return newBorn;
}
完整代码和演示:


非成员
操作符+
如何?您可以向前声明dog声明使用的类。只需在
dog
之前添加
类cat;类catdog;
,它就会知道其他类的存在。(还可以用
终止每个类;
)。是的,我实际上是从头开始输入代码,而不是复制我正在处理的代码,提交后意识到我忘记了在类上终止。>。我试图向前声明类,但仍然收到错误,告诉我不完整类的使用无效。看起来不错,作为非membe,运算符重载有什么缺点吗其类的r?@Mowen非成员运算符无法访问类的私有成员。但可以使用进行管理。