首页 > 解决方案 > C ++重载+运算符用于具有不同数据类型的两个对象

问题描述

我必须使用模板,因为要求 x、y、z 可以是任何类型(int、float、double、long 等)。

#include <conio.h>
#include <iostream>
using namespace std;

template <class T>
class TVector //this class is for creating 3d vectors
{
    T x, y, z;
    public:
    TVector() //default value for x, y, z
    {
        x = 0; 
        y = 0; 
        z = 0;
    }
    TVector(T a, T b, T c)
    {
        x = a; y = b; z = c;
    }

    void output()
    {
        cout << x << endl << y << endl << z;
    }

    //overloading operator + to calculate the sum of 2 vectors (2 objects)
    TVector operator + (TVector vec) 
    {
        TVector vec1;
        vec1.x = this->x + vec.x;
        vec1.y = this->y + vec.y;
        vec1.z = this->z + vec.z;
        return vec1;
    }
};

int main()
{
    TVector<int> v1(5, 1, 33); 
    TVector<float> v2(6.11, 6.1, 5.1);
    TVector<float> v3;    

    v3 = v1 + v2;
    v3.output();

    system("pause");
    return 0;
}

如果对象v1是浮动的,那么上面的代码将完美运行。然而,要求是向量 v1 具有int作为其数据类型。我该如何解决这个问题?

我已经尝试使用模板来重载 + 运算符,我的代码如下所示:

template <typename U>
TVector operator+(TVector<U> vec)
{
    TVector vec1;
    vec1.x = this->x + vec.x;
    vec1.y = this->y + vec.y;
    vec1.z = this->z + vec.z;
    return vec1;
}; 

^ 仍然不起作用: 在此处输入图像描述

标签: c++operator-overloading

解决方案


operator+您的问题与重载无关(或很少) 。编译器错误说明了一切:v1 + v2产生一个类型的向量TVector<int>(因为这就是你定义的方式operator+),并且你试图将它分配给v3类型TVector<float>。但是您还没有TVector为不同类型的 s 定义赋值运算符(这正是编译器在错误消息中告诉您的内容)!


推荐阅读