gpt4 book ai didi

c++ - 是否可以使用 '+' 运算符添加同一类的两个对象

转载 作者:太空狗 更新时间:2023-10-29 20:25:31 24 4
gpt4 key购买 nike

我的教科书说我们可以添加同一类的两个对象。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);
}

可以查看有关运算符重载的更完整引用here .

关于c++ - 是否可以使用 '+' 运算符添加同一类的两个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23718850/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com