分离的 cpp 上的 C++ ostream 重载

C++ ostream overload on separated cpp

我是 C++ 的新手,正在阅读 Stroustrup 的书,但我对 class 的运算符重载有疑问。我有这 3 个文件:

我像往常一样有两个文件,在 header 中我有定义:

#ifndef EQUATIONS_H
#define EQUATIONS_H

#include<vector>

namespace equations {

 //solve second degree equation
 class eqSecDeg {

  private:
   double a;
   double b;
   double c;
   std::vector<double> solArray;
   double getDelta(double a, double b, double c);

  public:
   eqSecDeg(const double valA, const double valB, const double valC);
   double getDelta();
   std::vector<double> getSolutions();

   //thrown with the error
   class EquationError {

    private:
     char* msg;
     int error_number;

    public:
     char* getMsg() { return msg; }
     EquationError(char* a = "Error.", int err = 0) {
      msg = a;
      error_number = err;
     };

   };

   //std::ostream& operator << (const std::ostream& x, eqSecDeg& A);
   // ^ is commented but it gives the error that it should be declared with only 1 parameter (?)    

 };

}

#endif

在这里你可以看到 dqsecdegree.cpp:

的实现
#include<math.h>
#include "dqsecdegree.h"

namespace equations {

 double eqSecDeg::getDelta(double a, double b, double c) {
  return (b*b)-(4*a*c);
 }

 double eqSecDeg::getDelta() {
  return (b*b)-(4*a*c);
 }

 //constructor
 eqSecDeg::eqSecDeg(const double valA, const double valB, const double valC) {

  if (valA == 0) {
   throw EquationError("Parameter 'a' cannot be zero.", 1);
  }

  a = valA;
  b = valB;
  c = valC;

 }

 std::vector<double> eqSecDeg::getSolutions() {

  double delta = getDelta(a,b,c);

  if (delta >= 0) {

   //x1 real and complex
   solArray.push_back( (-b+sqrt(delta))/(2*a) );
   solArray.push_back(0);
   //x2 real and complex
   solArray.push_back( (-b-sqrt(delta))/(2*a) );
   solArray.push_back(0);

  } else {

   delta *= -1;

   //x1 real and complex
   solArray.push_back( -b/(2*a) );
   solArray.push_back( (sqrt(delta)/(2*a)) );
   //x2 real and complex
   solArray.push_back( -b/(2*a) );
   solArray.push_back( -(sqrt(delta)/(2*a)) );

  }

  return solArray;

 }

 std::ostream& eqSecDeg::operator << (std::ostream& x, eqSecDeg& A) {
  return x << "something here";
 }

}

SO 和 google 上有很多答案,但我找不到正确的答案。我试图了解如何使用运算符重载。 我想在 header 文件中声明运算符重载及其在 cpp 上的实现是正确的。

我不知道我必须在哪里(以及如何)实施它。有什么建议吗?


不太相关,但主要是这样做的:

//a, b, c taken from the cin istream
equations::eqSecDeg solver(a,b,c);
std::vector<double> soluzioni = solver.getSolutions();

//here I'd like to call this
std::cout << solver;
  1. 在.h文件中将函数声明为非成员函数。

    std::ostream& eqSecDeg::operator<<(std::ostream& x, eqSecDeg const& A);
    
  2. 像您一样在 .cpp 文件中实现函数。更新它以使用 const& 而不是非常量 &.

  3. 随处使用。

    eqSecDeg A;
    
    ...
    
    std::cout << A << std::endl;