gpt4 book ai didi

c++ - 如何创建 operator*(double) 以在左侧和右侧进行乘法运算?

转载 作者:太空狗 更新时间:2023-10-29 21:32:52 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何为我的 Vector2d 类编写一个重载运算符,它允许我在左侧和右侧乘以一个标量。

class Vector2d
{
double _x;
double _y;

public:
Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

Vector2d operator*(const double s) const
{ return Vector2d(_x * s, _y * s); }

friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
return Vector2d(v._x * s, v._y * s);
}

如果我只定义成员运算符*,我的对象可以在右边乘以一个标量,但不能在左边。如果我添加友元函数operator*,编译时会报错:

Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'
Vector2D.h:61: first defined here
Vector2D.h:61: multiple definition of `Gf::operator*(double, Gf::Vector2d const&)'

正确的做法是什么?


我将 operator* 函数放在头文件中。一旦我将它移动到 .cpp,它就可以正确编译。

最佳答案

看起来你的文件被包含了多次,大多数编译器都支持#pragma once这些日子。您还可以使用 header 保护(在定义标记的定义之前检查标记的定义以及 header 的其余部分):

#ifndef VECTOR_2D
#define VECTOR_2D

class Vector2d
{
double _x;
double _y;

public:
Vector2d(double x = 0, double y = 0) :_x(x), _y(y) {}

Vector2d operator*(const double s) const
{ return Vector2d(_x * s, _y * s); }

friend Vector2d operator*(const double s, const Vector2d& v);
};

Vector2d operator*(const double s, const Vector2d& v)
{
return Vector2d(v._x * s, v._y * s);
}

#endif // VECTOR_2D

关于c++ - 如何创建 operator*(double) 以在左侧和右侧进行乘法运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53585467/

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