我是C ++的初学者,特别是数据结构。这个项目我们正在使用截断系列(类似的东西)。我得到这个奇怪的编译错误,我不知道它告诉我什么。在我创建复制构造函数之前程序运行正常,这可能是罪魁祸首。我很难做一个,但我不确定这是不是我应该这样做。
错误看起来像这样:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ostream:1077:1: note:
candidate template ignored: could not match
'basic_string<type-parameter-0-0, type-parameter-0-1, type-parameter-0-2>'
against 'Series'
operator<<(basic_ostream<_CharT, _Traits>& __os,
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ostream:1094:1: note:
candidate template ignored: could not match
'shared_ptr<type-parameter-0-2>' against 'Series'
operator<<(basic_ostream<_CharT, _Traits>& __os, shared_ptr<_Yp> const& __p)
^
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/ostream:1101:1: note:
candidate template ignored: could not match 'bitset<_Size>' against
'Series'
operator<<(basic_ostream<_CharT, _Traits>& __os, const bitset<_Size>& __x)
代码:
#include <iostream>
#include <vector>
using namespace std;
class Series {
private:
size_t degree;
vector <double> coefs;
public:
Series():degree(0){ }
Series(size_t d): degree(d){
for(int i = 0; i < (degree+1); i++){
coefs.push_back(0.0);
}
}
Series(double term){
coefs[0] = term;
}
Series(size_t d2,vector <double> newcoeffs): Series(d2) {
for (int i = 1; i < (d2+1); i++) {
coefs.at(i) = newcoeffs.at(i-1);
}
}
Series(const Series & rhs) {
degree = rhs.degree;
vector <double> coefs;
for (int i = 1; i < (degree+1); i++) {
coefs.at(i) = rhs.coefs.at(i);
}
}
~Series() {
coefs.clear();
}
void print(ostream & out) const{
if (degree == 0) {
return;
}
for (int i = 1; i < degree+1; i++)
out << coefs[i] << "x^" << i << " + ";
out << coefs[0];
}
};
ostream & operator <<(ostream & out, const Series & s){
s.print(out);
return out;
}
int main(){
vector <double> v {2.1,3.5,6.2};
vector <double> z {1.1,2.3,4.0};
Series two(3,z);
Series one(two);
cout << one << end;
cout << two << endl;
return 0;
}
答案 0 :(得分:3)
这只是您main
cout << one << end;
应该是
cout << one << endl;
您收到的无用错误消息是因为end
是std
命名空间中已存在的函数的名称。这是using namespace std;
经常为advised against的原因的一个很好的例子。
答案 1 :(得分:0)
与您的问题没有直接关系,但您的代码会导致std::out_of_range
异常。这是因为您使用at
,威尔是访问std::vector
内部值的函数,而不是在其中添加值。
for (int i = 1; i < (degree+1); i++)
// SEGFAULT !
coefs.at(i) = rhs.coefs.at(i);
您必须使用std::vector::push_back
在容器中添加元素。
for (int i = 1; i < (degree+1); i++)
coefs.push_back(rhs.coefs.at(i));
现代C ++甚至更短:
for (auto elem : rhs)
coefs.push_back(elem);