我的教科书说我们可以添加两个相同类的对象。V3 = V2 + V1 //全部属于同一类。
但是,当我在Turbo c ++中进行测试时,出现错误:指向同一行的非法结构操作V3 = V1 + V2。
所以我的问题是是否可以使用+运算符添加两个相同类的对象,如果答案为是,那么为什么会收到错误消息?
您的班级必须使+
操作员超载。没有它,编译器将不知道如何“添加”给定的两个类。+
通过添加运算符重载功能来定义运算符应如何工作。
以下是“ V”类的示例:
V V::operator+(const V& other){
//Define how should the classes be added here
//Example addition of private fields within V
int field1 = this.field1 + other.field1;
//Return the 'added' object as a new instance of class V
return V(field1);
}
可以在此处查看有关操作员重载的更完整参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句