Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/154.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;测试过载+;操作人员_C++_Operator Overloading - Fatal编程技术网

C++ C++;测试过载+;操作人员

C++ C++;测试过载+;操作人员,c++,operator-overloading,C++,Operator Overloading,我只是简单地添加两个大小为3的数字数组并打印结果。因此,如果: A=4,6,1 B=8,5,6 那么结果是12,11,7。我的问题是我正在打印指数数字,即-1.28823e-231。谁能告诉我为什么?我已经尽力在这里保留尽可能少的代码。首先是main(),然后是页眉,然后是源材质。非常感谢 NumericArray<double> doubArray5; //test + operator cout << "doubArray5" << endl; do

我只是简单地添加两个大小为3的数字数组并打印结果。因此,如果: A=4,6,1 B=8,5,6 那么结果是12,11,7。我的问题是我正在打印指数数字,即-1.28823e-231。谁能告诉我为什么?我已经尽力在这里保留尽可能少的代码。首先是main(),然后是页眉,然后是源材质。非常感谢

NumericArray<double> doubArray5;    //test + operator
cout << "doubArray5" << endl;
doubArray5 = doubArray2 + doubArray3;
for (int i = 0; i < doubArray5.Size(); i++)
    cout << doubArray5[i] << endl;
cout << endl;

#ifndef NUMERICARRAY_H
#define NUMERICARRAY_H
#include "array.h"
#include <iostream>

namespace Cary
{
    namespace Containers
    {
        template<typename T>
        class NumericArray: public Array<T>
        {
        public:
            NumericArray<T>();    //default constructor
            NumericArray<T>(int i);    //constructor with one argument
            ~NumericArray<T>();    //destructor
            NumericArray<T>(const NumericArray<T>& source);    //copy constructor
            NumericArray<T>& operator = (const NumericArray<T>& arr1);    //assignment operator
            NumericArray<T> operator * (double factor) const;    //scale
            NumericArray<T>& operator + (const NumericArray<T>& arr2) const;    //add
            T dotProduct(const NumericArray<T>& na) const;    //dot product
        };
    }
}
#ifndef NUMERICARRAY_CPP
#include "NumericArray.cpp"
#endif
#endif

template<typename T>
NumericArray<T>& NumericArray<T>::operator + (const NumericArray<T>& arr) const    //add
{
    if (Array<T>::Size() != arr.Size()) throw OutOfBoundsException();
    NumericArray<T> tempArray = NumericArray(Array<T>::Size());
    for (int i = 0; i < Array<T>::Size(); i++)
        tempArray[i] = Array<T>::GetElement(i) + arr.GetElement(i);
    return tempArray;
}
numericarraydoubarray5//测试+操作员
cout习惯用法(即,根据重载数值运算符时的“行为类似于int”准则),
运算符+()
通常按值返回,而不是按引用返回,因为加法的结果是一个不同于所添加值(或对象)的值(或对象)


具体地说,正如Mike Seymour在评论中提到的,您的
操作符+()
返回对局部变量的引用,该局部变量在
操作符+()
返回时不再存在。如果调用方随后尝试使用返回的引用,则会导致调用方表现出未定义的行为。

您正在返回对局部变量的引用(
operator+
中的
tempArray


当函数返回时,
tempArray
被销毁。然后,调用方尝试使用对现在已销毁的对象的引用,并读取垃圾。

打开编译器警告-它们应该告诉您正在返回对局部变量的引用,该局部变量在您对其执行任何操作之前已销毁<代码>运算符+
和类似运算符通常必须返回一个值。