c ++ debug'<<'找不到操作员

时间:2015-11-19 20:23:50

标签: c++ debugging

我正在尝试在c ++上运行以下代码,但仍然存在geting错误。任何人都可以帮我解决。 来自c ++的错误消息说:

  

错误6错误C2679:二进制'<<' :找不到哪个运营商需要   “MVector”类型的右侧操作数

 #include <iostream>
 #include <cmath>
 #ifndef MVECTOR_H // the 'include guard'
 #define MVECTOR_H // see C++ Primer Sec. 2.9.2
 #include <vector>
 #include <string>
 #include <fstream>

 class MVector
 {
 public:
     // constructors
     MVector() {}
     explicit MVector(int n) : v(n) {}
     MVector(int n, double x) : v(n, x) {}

     void push_back(double x)
     {
         v.push_back(x);
     }

     double AV()
     {
         double sum = 0.0, average = 0.0;
         for (double i = 0; i<v.size(); i++)
         {
             sum += v[i];
         }
         average = sum / v.size();
         return average;
     }

     MVector RunningAverage(int m, int p)
     {
         MVector movingaverage(v.size() - m - p - 1);
         for (int i = m; i < v.size() - p; i++)
         {
             double sum = 0.0;
             if ((i + p < v.size()))
             {
                 for (int j = i - m; j <= i + p; j++)
                 {
                     sum += v[j];
                     movingaverage[i - m] = sum / (m + p + 1);
                 }
             }
         }
         return movingaverage; // Edit by jpo38
    }

    // access element (lvalue)
    double &operator[](int index) { return v[index]; }
    // access element (rvalue)
    double operator[](int index) const { return v[index]; }
    int size() const { return v.size(); } // number of elements

private:
    std::vector<double> v;
};
#endif

int main()
{
    using namespace std; 
    // create an MVector
    MVector x;
    // add elements to the vector
    x.push_back(1.3);
    x.push_back(3.5);
    x.push_back(3.0);
    x.push_back(2.0);
    // x now contains 1.3 and 3.5
    // print x
    std::cout << " x:= ( ";
    for (int i = 0; i < x.size(); i++)
        std::cout << x[i] << " ";
    std::cout << ")\n";
    std::cout << x.RunningAverage(0, 1.0) << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:1)

x.RunningAverage(0, 1.0)会返回无法发送到MVector的{​​{1}},除非您声明std::coutoperator<<作为参数。

或者,您可以替换:

MVector

人:

std::cout << x.RunningAverage(0, 1.0) << endl;

或者,声明运营商:

MVector av = x.RunningAverage(0, 1.0);
for (int i = 0; i < av.size(); i++)
    std::cout << av[i] << " ";

然后std::ostream& operator<<(std::ostream& out,const MVector& b) { for (int i = 0; i < b.size(); i++) out << b[i] << " "; return out; } 将起作用。

然后您还可以在std::cout << x.RunningAverage(0, 1.0) << std::endl;函数中替换

main

人:

for (int i = 0; i < x.size(); i++)
    std::cout << x[i] << " ";

现场演示:http://cpp.sh/7afyi

答案 1 :(得分:0)

您尚未为operator<<重载MVector

你可以这样做:

std::ostream& operator<<(std::ostream& output, MVector const& vec)
{
    // use "output << …;" to do printing
    return output;
}