C++ 调试"<<"未找到运算符

c++ debug '<<' no operator found

本文关键字:lt 运算符 C++ 调试      更新时间:2023-10-16

我正试图在c++上运行以下代码,但不断出现错误。有人能帮我解决吗。来自c++的错误消息说:

错误6错误C2679:二进制'<lt;':找不到需要"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;
}

x.RunningAverage(0, 1.0)返回一个不能发送到std::coutMVector,除非您声明operator<<使用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] << " ";

签字人:

std::cout << x;

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

您没有为MVector重载operator<<

你可以用

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