可以将整数、 float 、 double 或任何其他可转换为 float 的 C++ 函数

标签 c++ c++11 c++14

我正在尝试用 C++ 实现 Vector3 结构。我正在重载“*”运算符来处理与标量值的乘法。所以它会像这样工作:

v1 = Vector3(1.0f, 1.0f, 1.0f);
v2 = 2*v1;
v3 = 2.4f*v1;
v4 = 2.4*v1;

所有 3 个操作都将返回一个 Vector3 实例。但是,我不想为此目的实现 3 个函数。

    Vector3 operator * (int& const val) {
       float _val = static_cast<float> (val);
       return Vector3(x * _val, y * _val, z * _val);
    }

   Vector3 operator * (double& const val) {
           float _val = static_cast<float> (val);
           return Vector3(x * _val, y * _val, z * _val);
   }
   
   Vector3 operator * (float& const val) {
               return Vector3(x * val, y * val, z * val);
       }
    

有没有更好的方法用一个函数来做到这一点?

最佳答案

由于您要将所有类型再次转换为 float,因此您不需要这样做。

如果您将函数定义为接受 float,然后传递 int 或任何可转换类型,它将自动转换为 float 。下面的代码表明

#include <typeinfo>
#include <iostream>

struct Vector3
{
    Vector3(float x, float y, float z): x{x}, y{y}, z{z}{}
    float x, y, z;
    Vector3 operator*(float val)const{
        return Vector3{val * x,val * y,val * z};
    }
};

int main(){
    Vector3 v1{1,2,3};
    auto v2 = v1*2;
    std::cout << typeid(v2.x).name();
}

Live

如果你想以相反的顺序使用乘法

#include <typeinfo>
#include <iostream>

struct Vector3
{
    Vector3(float x, float y, float z): x{x}, y{y}, z{z}{}
    float x, y, z;
};
Vector3 operator*(float val, const Vector3& v){
    return Vector3{val * v.x,val * v.y,val * v.z};
}

int main(){
    Vector3 v1{1,2,3};
    auto v2 = 2*v1;
    std::cout << typeid(v2.x).name();
}

为了简单起见,我使用了公共(public)成员。你可能想将私有(private)的与 setter 和 getter 一起使用。

关于可以将整数、 float 、 double 或任何其他可转换为 float 的 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63093618/

相关文章:

c++11 - 融合改编的 std_tuple View ,转换为另一个元组

C++11 通过引用定义函数类型捕获

opencv - 尽管捕获了OpenCV VideoWriter,但仍在全盘上引发运行时错误

c++ - 具有互斥数据成员的对象的设计替代方案

c++ - std::equal 与 reverse_iterator

c++ - 链接器在 Eclipse/JNI/ANT 中找不到库

c++ - 我可以获得适用于任何数字类型的模板化均匀分布生成器吗?

c++ - 如何使用模板元编程重构此循环?

c++ - 唯一命名对象表

C++ block scope extern declaration linkage,混淆C++标准解释