我的教科书说我们可以添加两个相同类的对象.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);
}
Run Code Online (Sandbox Code Playgroud)
可以在此处查看有关运算符重载的更完整参考.