简体   繁体   English

在模板类数组中重载乘法运算符

[英]Overloading a multiplication operator in a template class array

I'm trying to code a template class for making arrays that has an overloaded multiplication operator. 我正在尝试编写一个模板类来制作具有重载乘法运算符的数组。 The actual insides of the template class appear fine, however I am having trouble with the overloading of the * operator. 模板类的实际内部看起来不错,但是我在*运算符的重载方面遇到了麻烦。 I originally had an overloaded operator for multiplying arrays in a regular class, here I am using that first overloaded operator as a base for the template. 我最初有一个用于在常规类中乘法数组的重载运算符,这里我使用的是第一个重载运算符作为模板的基础。

This is whats in my header file : 这是我的头文件中的内容:

operator * (const Array<T>& a) const;  //*  operator

And this is whats in my main file : 这就是我的主文件:

template <class T>
Array<T>::operator * (const Array<T>& a) const
{
   if (num != a.num)
   {
       cout << "Error, arrays not equal!" << endl;
   }

   Array<int> tmp;
   delete[] tmp.data;

   tmp.data = new int[cap];
   tmp.num = a.num;
   tmp.cap = a.cap;

   memcpy(tmp.data, a.data, sizeof(int)*num);


   for(int i = 0 ; i < num ; i++)
   {
       tmp.data[i] = tmp.data[i] * a.data[i];
   }  

   return tmp;
}

The error I am receiving is telling me that something is wrong with tmp. 我收到的错误告诉我tmp出了点问题。 It states "error: cannot convert 'Array' to 'int' in return" in reference to "return tmp" at the end of the function. 它指出“错误:无法将'Array'转换为'int'作为回报​​”,并在函数末尾引用了“ return tmp”。

I am trying to multiply two arrays (a and c) created in main() 我试图乘以main()中创建的两个数组(a和c)

Array <int> d = a * c;

There are error messages relating to Array d, but those also appear to be rooted in the error inside the overloaded operator function. 存在与数组d有关的错误消息,但这些错误消息似乎也源于重载运算符函数内部的错误。 How is tmp being turned into 'int' ? tmp如何变成'int'?

Your function does not have a return type. 您的函数没有返回类型。 C++ will therefore default to int . 因此,C ++将默认为int to solve this, make sure the function returns an Array<int> (the type of tmp). 要解决此问题,请确保该函数返回Array<int> (tmp的类型)。

You need to template Array<int> tmp; 您需要模板Array<int> tmp; as Array<T> tmp; Array<T> tmp; , so that then you memcpy(tmp.data, a.data, sizeof(int)*num); ,这样您就可以使用memcpy(tmp.data, a.data, sizeof(int)*num); the size of memory area would realy be same. 内存区域的大小实际上是相同的。 Also, as @Thecocatrice mentioned, add retutn type to you overloaded operator. 另外,如@Thecocatrice所述,向您重载的运算符添加retutn类型。 This will look like 这看起来像

template<typename T>
Array<T> Array<T>::operator *(const Array<T> &a) { ... };

And last. 最后。 You dont actually need that memcpy . 您实际上不需要该memcpy It doesnt make any sence, since you still have loop. 它没有任何意义,因为您仍然有循环。 Just write: 写吧:

for(int i = 0 ; i < num ; i++)
{
    tmp.data[i] = data[i] * a.data[i];
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM