代码之家  ›  专栏  ›  技术社区  ›  Trần Đức Hiếu

两个数据类型不同的对象的C++重载+运算符

  •  -4
  • Trần Đức Hiếu  · 技术社区  · 7 年前

    我必须使用模板,因为要求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 如果是float,则上述代码将完美运行。然而,要求向量v1具有 内景 作为其数据类型。如何解决此问题?

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

    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;
    }; 
    

    ^仍然不起作用: enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dan M.    7 年前

    你的问题与 operator+ 超载。编译器错误说明了一切: v1 + v2 生成类型为的向量 TVector<int> (因为这就是您定义 操作员+ ),您正在尝试将其分配给 v3 的类型 TVector<float> 。但您尚未为定义赋值运算符 TVector 不同类型的(这正是编译器在错误消息中告诉您的)!