gpt4 book ai didi

c++ - 运算符关键字c++

转载 作者:可可西里 更新时间:2023-11-01 18:17:17 26 4
gpt4 key购买 nike

我们有以下类(class)。我需要对部分代码进行解释。

class CPoint3D
{
public:
double x, y, z;

CPoint3D (double dX = 0.0, double dY = 0.0, double dZ = 0.0)
: x(dX), y(dY), z(dZ) {}
//what means these lines of code?
CPoint3D operator + (const CPoint3D& point) const;
CPoint3D operator - (const CPoint3D& point) const;
CPoint3D operator * (double dFactor) const;
CPoint3D operator / (double dFactor) const;
};

我想用

CPoint3D 运算符 + (const CPoint3D& point) const;

函数我可以轻松地添加/减去/乘/除CPoint3D 类的实例?

有人可以举例说明吗?谢谢!

最佳答案

网络上有数以百万计的示例和/或文章(包括 this one ),所以我不会在这里重复它们。

可以这么说,当您使用 obj1 + obj2 将两个 CPoint3D 对象相加时,调用的函数是该类的 operator+ ,其中一个对象是 this,另一个是 point

您的代码负责创建另一个包含这两个相加的对象,然后返回它。

减法同上。乘法运算符略有不同,因为它们使用 double 作为另一个参数 - 大概虽然为加法运算符添加/减去类的各个成员是有意义的,但这对乘法运算符没有用

关于c++ - 运算符关键字c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18269232/

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