我是C++的初學者,尤其是數據結構。這個項目我們正在使用截斷系列(類似的東西)。我收到了這個奇怪的編譯錯誤,我不確定它告訴我什麼。該程序運行正常之前,我創建了複製構造函數,以便可能是罪魁禍首。我很難做出一個,但我不知道這是我應該如何。複製構造函數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;
}
'coefs.at(I)= rhs.coefs.at(I);'將有可能導致分段錯誤,因爲你的容器有之前未被初始化。 – informaticienzero
我認爲你必須將你的<<運算符聲明爲朋友運算符,並在類之外定義它。 –
@informaticienzero我現在得到這個:libC++ abi.dylib:終止與類型std :: out_of_range的未捕獲的異常:向量 中止陷阱:6,這是否有什麼關係?我如何解決它? –