如果只能通过存储在数组中的共享指针访问对象,如何调用函数?

时间:2015-03-05 15:38:54

标签: c++ arrays pointers

我正在制作一个可以求解多项式的程序(从.txt文件读入)。我已经让程序工作到读取文件并从类Polynomial的信息中生成一个对象,然后存储指向数组中该多项式对象的共享指针。这样,如果我愿意,我可以在for循环中访问多项式对象。但是,我试图找到一个函数来评估x替换为x的任何数字的多项式。例如,如果我的多项式是3x ^ 2 + 11x + 9,并且我想在x = 7时求解多项式,我只是将7 in作为eval函数的参数,它将解决它。我的问题是,如果指向该对象的指针位于数组中,我不知道如何在对象上调用函数。这是我的代码:

#include "polynomial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>       // for exit() call

using namespace std;


void makePolynomials( shared_ptr<Polynomial> pointer1 [], int &x );


int main()
   {
   shared_ptr<Polynomial> poly[ 100 ];
   int nPolynomials = 0;

   makePolynomials( poly, nPolynomials );
   makePolynomials( poly, nPolynomials );

   // print out the polynomials
   // -------------------------
   for (int j=0; j < nPolynomials; j++)
      cout << *(poly[j]);

    if(*(poly[0]) == *(poly[1]))
    {
        cout << "true" << endl;
    }
    else
    {
        cout << "they are false" << endl;
    }

}


void makePolynomials( shared_ptr<Polynomial> poly[], int &nPolynomials )
   {
   // get the filename from the user and open the file
   // ------------------------------------------------
   char filename[20];
   cout << "Enter the filename: ";
   cin >> filename;

   ifstream infile;
   infile.open( filename );
   if (! infile.is_open()) {
      cerr << "ERROR: could not open file " << filename << endl;
      exit(1);
      }

   // read in the data and construct a polynomial for each input line
   // ---------------------------------------------------------------
   string polynom;
   while (getline( infile, polynom ))
      {
      poly[ nPolynomials ] = shared_ptr<Polynomial>(new Polynomial( polynom ));
      nPolynomials++;
      }
   }

polynomial.cpp文件

#include "polynomial.h"
#include <sstream>
#include <cmath>


double Polynomial::TOL = .000000000001;   // tolerance for floating pt. equality

//+------------------+
//| Term constructor |
//+------------------+
Polynomial::Term::Term( double c, int e, shared_ptr<Term> n )
   {

   coeff = c; exponent = e; next = n;

   }

//+--------------------------------------+
//| Default Constructor: Polynomial is 0 |
//+--------------------------------------+
Polynomial::Polynomial()
   {
   head = nullptr;
   }

//+-------------------------------------------------------------+
//| Constructor: The input string contains coefficient-exponent |
//| pairs where everything is separated by whitespace           |
//+-------------------------------------------------------------+
 Polynomial::Polynomial( string & str )
   {
   stringstream ss( str );  // stringstream lets us extract items separated by
                            // whitespace simply by using the >> operator
   double coefficient;      // to hold the coefficient
   int exp;                 // to hold the exponent
   head = nullptr;          // initialize head to null

   // read in coefficient-exponent pairs and add each term to the list
   // ----------------------------------------------------------------
   while (ss >> coefficient >> exp)
      if (coefficient != 0)   // don't make a 0 term
         head = shared_ptr<Term>(new Term( coefficient, exp, head ));
   }



Polynomial &Polynomial::operator=( const Polynomial &rhs )
   {
   }



bool Polynomial::operator==( const Polynomial &other ) const
   {
    shared_ptr<Polynomial::Term> current1 = other.head;
    shared_ptr<Polynomial::Term> current2 = head;

        while ((current1 != NULL) && (current2 != NULL))  // checks to see if they're valid. if not, it stops
        {
            //check to see if coeff and exp match
            if( (current1->coeff == current2->coeff) && (current1->exponent == current2->exponent) )
            {
                // if they match and their next node is empty
                if ((current1->next == NULL) && (current2->next == NULL))
                {
                    return true;
                }
                // continue down the polynomial
                else
                {
                    current1 = current1->next;
                    current2 = current2->next;
                }
            }
            else
            {
                return false;
            }
        }
         return false; // if it never runs the loop, it will return false
   }







bool Polynomial::operator!=( const Polynomial &other ) const
   {
   }


Polynomial Polynomial::operator+( const Polynomial &other ) const
   {
       //shared_ptr<Polynomial> result = shared_ptr<polynomial>(new Polynomial()); // where you are going to store your results
       //shared_ptr<Polynomial::term> a = head;
    //shared_ptr<term>b = other.head
    //while(a! = nullptr && b! = nullptr){
      //  term(a->coeff, a->expon, nullptr)
        //if (current->exponent == 0)
          //  os << current->coeff;
        //else if (current->coeff == 1)
          //  os << "x^" << current->exponent;
        //else
          //  os << current->coeff << "x^" << current->exponent;

   }


//+---------------------------------------------------------------+
//| Compute and return the value of the polynomial evaluated at x |
//+---------------------------------------------------------------+
double Polynomial::eval( double x ) const
   {
        double number = x;
        double product1 = 0;
        shared_ptr<Polynomial::Term> current = head;


        while(head != nullptr)
        {
            product1 = pow(number, current->exponent);
            current = current ->next;
            return product1;

        }
               // for(traverse; traverse!=nullptr; traverse = traverse->head)
               // cout <<  <<endl;
        }





//+--------------------------------------------------------------------------+
//| Overload the outstream << operator.  Doesn't print the variable for the  |
//| constant term.  Doesn't print "1" coefficients unless it is the constant |
//| term.  Prints the sign of the coefficient as addition or subtraction.    |
//+--------------------------------------------------------------------------+
ostream &operator<<( ostream &os, const Polynomial &poly )
   {
   // special case for 0 polynomial
   // -----------------------------
   if (poly.head == nullptr)
      {
      os << "0" << endl;
      return os;
      }

   shared_ptr<Polynomial::Term> current = poly.head;

   // print the first term separately since no leading + or - sign
   // ------------------------------------------------------------
   if (current->exponent == 0)
      os << current->coeff;
   else if (current->coeff == 1)
      os << "x^" << current->exponent;
   else
      os << current->coeff << "x^" << current->exponent;

   // print each remaining term along with leading addition or subt. sign
   // -------------------------------------------------------------------
   for (current = current->next; current != nullptr; current = current->next)

      if (current->coeff > 0)   // positive term?
         {
         if (current->exponent == 0)
            os << " + " << current->coeff;        // a constant term
         else if (current->coeff == 1)
            os << " + x^" << current->exponent;   // no 1 coeffienct
         else
            os << " + " << current->coeff << "x^" << current->exponent;
         }
      else  // negative term
         {
         if (current->exponent == 0)
            os << " - " << -current->coeff;       // a constant term
         else if (current->coeff == -1)
            os << " - x^" << current->exponent;   // don't print the 1
         else
            os << " - " << -current->coeff << "x^" << current->exponent;
         }

   os << endl;  // print the newline character and flush the output stream
   return os;
   }

我试图在主要内容中写出类似的内容......

*(poly[0])->eval(7);

但是我收到一条错误消息,指出shared_ptr没有成员eval。我不明白为什么这是因为eval是在类Polynomial的公共访问器下的头文件中的原型?

2 个答案:

答案 0 :(得分:1)

表达式*(poly[0])取消引用数组中第一个位置的shared_ptr:

Polynomial& p = *(poly[0]);

您的表达式*(poly[0])->eval(7);将等同于

Polynomial& p = *(poly[0]);
p->eval(7);

不能用作p不是指针。您可以使用poly[0]->eval(7);实现所需的功能,相当于

shared_ptr<Polynomial>& p = poly[0];
p->eval(7);

shared_ptr以这样的方式实现operator->,它返回一个指向托管实例的指针,因此您可以使用此运算符来调用eval方法。另请参阅shared_ptr文档。

答案 1 :(得分:0)

为了完成上面的答案,你应该使用static_cast进行强制转换,所以至少编译器会告诉你为什么你在做什么不起作用。

可能,声明:

*(poly[i])->eval(7)

被解释为:

  1. 获取多边形阵列中的第i个项目
  2. 尝试在(预期)指针上调用 eval 方法,但这不起作用,因为多边形数组的第i项是对shared_ptr对象的引用,而不是多项式< / LI>
  3. 取消引用方法的结果(返回)
  4. 在您的代码中,您可以使用:

    static_cast<Polynomial&>(*poly[0]).eval(7)
    

    告诉编译器你要调用shared_ptr&lt; Polynomial&gt;的多项式&amp; 转换运算符。 class,然后,使用生成的引用的Polynomial实例,调用eval方法。