C 超载 运算符,因此您可以在该类中添加不同的类并获得第三类
C++ overload the + operator of a class so you can add a different class to that class and get a third class
所以我只是在玩耍,但是我想看看是否可以超载班级的 运算符,以允许它不将其添加在一起,但将其添加到一个二等级别并因此获得了第三类。
示例:
#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
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 只能向C++添加一定数量的字符
- Qt和C++:将QLineEdit添加到QTabWidget中
- 将QIcon添加到QTableView单元格
- 为什么我必须在C++中添加一个赋值符号来声明一个数组
- 为什么除非添加括号,否则构造函数上的模板替换会失败?
- 将图像添加到资源文件夹UWP C++
- C 超载 运算符,因此您可以在该类中添加不同的类并获得第三类