分离的cpp

时间:2017-04-07 21:52:48

标签: c++ operator-overloading c++14 c++builder

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

enter image description here

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

#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和谷歌上有很多答案,但我找不到正确的答案。我试图了解如何使用运算符重载。 我想在头文件中声明运算符重载并在cpp上执行它的正确。

  • 为什么编译器告诉我参数太多?我确定(?)我需要其中2个(ostream和类)
  • 我知道friend关键字只提供对所有成员的访问权限,而不会使该方法成为该类的一部分。当我使用该关键字时,编译器告诉我没有int / double / char /的ostream输出的有效定义。 哪里我应该放置运算符重载定义吗?

我无法理解我必须在哪里(以及如何)实现它。有什么建议吗?

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

//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 个答案:

答案 0 :(得分:1)

  1. 将该函数声明为.h文件中的非成员函数。

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

  3. 在任何您喜欢的地方使用它。

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