请求C++从非标量类型转换为非标量类型
C++ conversion from to non-scalar type requested
我正在尝试将 + 运算符重载为成员函数,以便我可以将两个多项式对象(链表)添加在一起,并且不断收到错误消息conversion from 'Polynomial*' to non-scalar type 'std::shared_ptr<Polynomial>' requested
我不明白是什么原因造成的?我已经为我的 Term 对象声明了两个共享指针,所以我不明白为什么我不能为多项式对象执行此操作?
Polynomial Polynomial::operator+( const Polynomial &other ) const
{
shared_ptr<Polynomial> result = new Polynomial();
shared_ptr<Polynomial::Term> a = this->head;
shared_ptr<Polynomial::Term> b = other.head;
double sum = 0;
for(a; a != nullptr; a = a->next)
{
for(b; b != nullptr; b = b->next)
{
if(a->exponent == b->exponent)
{
sum = a->coeff + b->coeff;
result->head = shared_ptr<Term>(new Term( sum, a->exponent, result->head ));
cout << "function has found like terms" << endl;
}
else if(a->exponent != b->exponent)
{
result->head = shared_ptr<Term>(new Term( a->coeff, a->exponent, result->head ));
cout << "function is working" << endl;
}
}
}
result;
}
主.cpp
void makePolynomials( shared_ptr [], int &x );
int main()
{
shared_ptr<Polynomial> poly[ 100 ];
int nPolynomials = 0;
makePolynomials( poly, nPolynomials );
makePolynomials( poly, nPolynomials );
for (int j=0; j < nPolynomials; j++)
cout << *(poly[j]);
//shows that the addition operator works
Polynomial c;
c = *(poly[0])+*(poly[1]);
cout << c << endl;
}
void makePolynomials( shared_ptr<Polynomial> poly[], int &nPolynomials )
{
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);
}
string polynom;
while (getline( infile, polynom ))
{
poly[ nPolynomials ] = shared_ptr<Polynomial>(new Polynomial( polynom ));
nPolynomials++;
}
}
在这里,您请求从Polynomial*
到std::shared_ptr
的隐式转换:
shared_ptr<Polynomial> result = new Polynomial();
但是由于std::shared_ptr
构造函数是explicit
的,因此无法进行转换。
您需要将Polynomial*
显式传递给std::shared_ptr
构造函数:
std::shared_ptr<Polynomial> result(new Polynomial);
或使用等效的新统一初始化语法:
std::shared_ptr<Polynomial> result{new Polynomial};
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 特征中的自定义标量类型
- 标量类型的特征模板无法编译固定大小的子矩阵操作
- 请求从"点*"转换为非标量类型"点"
- 标量类型上的特征模板
- 错误:在 C++ 中从 'Counter' 转换为非标量类型'CountDn'
- 特征:从数组类型中获取标量类型是否记录?
- 错误:请求从"Mstream"转换为非标量类型"std::string {aka std::basic_string<char>}"
- Arduino trim() 和 replace() 方法返回从 'void' 到非标量类型'String'请求的转换
- 错误:移动文件时'QString'为非标量类型"std::__cxx11::字符串"
- 标量类型附加C++
- 复制初始化 - 从 'int' 类型转换为非标量类型
- 在 opencv 上将 vec 类型转换为标量类型
- 为矢量对象请求转换为非标量类型
- 错误:请求从 std::chrono::time_point 浮点数转换为非标量类型长整型
- 此错误的含义是什么:从 'char* [40] 转换为非标量类型 'std::string
- 小标量类型和谷歌协议缓冲区
- 我可以强制执行标量类型通过 int{} 初始化为零吗?