c++ - 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;
};
解决方案
operator+
您的问题与重载无关(或很少) 。编译器错误说明了一切:v1 + v2
产生一个类型的向量TVector<int>
(因为这就是你定义的方式operator+
),并且你试图将它分配给v3
类型TVector<float>
。但是您还没有TVector
为不同类型的 s 定义赋值运算符(这正是编译器在错误消息中告诉您的内容)!
推荐阅读
- c# - 为什么我的 C# 代码在回调到 C++ COM 时会停止,直到 Task.Wait/Thread.Join?
- extjs6 - Extjs 6.7 TreeList 从远程存储无限加载数据
- java - Selenium isSelected() 方法在说谎
- normal-distribution - 如何检查来自非常大样本的变量分布的正态性?
- java - 如何初始化 Activity 中定义的接口,该接口由通过 TabLayout 使用 ViewPager 设置的 3 个片段实现?
- java - 使用正则表达式提取字符串
- karate - 空手道 API json 响应 - 如何验证有时会出现但有时不会出现在 API 响应中的密钥的存在
- tensorflow - 云计算虚拟机与 AI 平台的性能差异
- wso2 - WSO2 SCIM2.0 API GET USERS 空结果
- c# - 如何加入列表数组值