如果对象只能通过存储在数组中的共享指针访问,如何调用函数?
How can I call a function if the object can only be accessed through a shared pointer that's stored in an array?
我正在制作一个可以求解多项式的程序(从.txt文件中读取)。我已经让程序工作到读取文件,并用类多项式的信息创建一个对象,然后在数组中存储一个指向该多项式对象的共享指针。这样,如果我想的话,我就可以访问for循环中的多项式对象。然而,我正在尝试对一个函数进行校正,该函数将评估用x代替的任何数字的多项式。例如,如果我的多项式是3x^2+11x+9,并且我想在x=7时求解多项式,我只需要将7作为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的公共访问器下的头文件中原型化的?
表达式*(poly[0])
取消引用数组中第一个位置的shared_ptr:
Polynomial& p = *(poly[0]);
那么你的表达式*(poly[0])->eval(7);
就等于
Polynomial& p = *(poly[0]);
p->eval(7);
其不能工作,因为CCD_ 3不是指针。你可以用poly[0]->eval(7);
实现你想要的,它相当于
shared_ptr<Polynomial>& p = poly[0];
p->eval(7);
shared_ptr
实现operator->
的方式是,它返回一个指向托管实例的指针,因此您可以使用此运算符来调用eval
方法。另请参阅shared_ptr文档。
为了完成上面的答案,您应该使用static_cast进行强制转换,这样至少编译器会告诉您为什么所做的操作不起作用。
很可能,声明:
*(poly[i])->eval(7)
解释为:
- 获取poly数组中的第i个项目
- 尝试在(预期的)指针上调用eval方法,但这不起作用,因为poly数组的第i项是对shared_ptr对象的引用,而不是多项式
- 取消引用方法的结果(返回)
在您的代码中,您可以使用:
static_cast<Polynomial&>(*poly[0]).eval(7)
这告诉编译器您想要调用多项式&shared_ptr<多项式>类,然后使用生成的引用多项式实例,调用eval方法。
- 函数何时会在c++中包含stack_Unwind_Resume调用
- 访问条件类成员的方法不仅在被调用时才编译
- 从C++调用 Python 并访问通过 Anaconda 安装的软件包
- 用户控制从 c++ 到 java 脚本的 Webassembly 访问调用
- 调用函数后无法访问数组
- 是否可以访问代码中的调用堆栈?
- 通过 id 访问 QML 插槽中的嵌套对象(从 c++ 调用)
- 在其他线程中循环访问该concurrent_vector时调用 concurrency::concurrent_vect
- 从Delphi调用C++DLL时发生访问冲突
- 在 C 代码中调用 Python 函数时第三次出现访问冲突写入位置错误
- C++ 基类调用已删除或无法访问的函数
- 访问并调用 std::function 的变体
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 为什么创建进程 API 调用会导致内存访问冲突?
- 引发访问冲突的 Win32 API 调用
- C ++尝试访问映射中的元素会给我一个不匹配的函数调用错误
- 通过在基类中虚拟调用派生类中的函数来访问派生类中的函数
- Lambda 函数,用于调用有权访问类成员的成员函数
- 油.dll调用 - 访问被拒绝错误80020009出错
- 多次调用访问器方法或声明临时变量是否更有效