inf*_*oop 4 c++ linked-list ostream
所以我无法弄清楚为什么我的插入操作符不能用于我的列表类.我已经看了一会儿,我认为重载的语法是正确的.在这一点上不确定.关于它为什么不工作的任何提示?这是代码:
编辑:将一些代码更改为当前的代码.
对不起,现在问题是我无法打印任何东西,简单的打印和空行.
这是司机:
#include <iostream>
#include "polynomial.h"
using namespace std;
int main(){
Polynomial* poly = new Polynomial();
poly->set_coefficient(3,2);
poly->set_coefficient(0,2);
poly->set_coefficient(3,1);
cout << "trying to print data" << endl;
cout << *poly << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是标题:
#ifndef _POLYNOMIAL_H_
#define _POLYNOMIAL_H_
#include <iostream>
class Polynomial {
public:
struct PolyNode {
int coefficient, degree;
struct PolyNode* next;
PolyNode(int c, int d, PolyNode* n): coefficient(c),degree(d),next(n){}
};
PolyNode* firstTerm;
Polynomial(): firstTerm(0) {}
struct PolyNode* get_first(){
return firstTerm;
}
//makes the term with degree d have a coefficient of c
void set_coefficient(int c, int d);
~Polynomial();
friend std::ostream& operator<<(std::ostream& o, const Polynomial& p);
};
#endif
Run Code Online (Sandbox Code Playgroud)
这是实施:
#include "polynomial.h"
#include <iostream>
#include <ostream>
using namespace std;
void Polynomial::set_coefficient(int c, int d){
PolyNode* start = firstTerm;
if(c != 0 && firstTerm == 0)
firstTerm = new PolyNode(c,d,NULL);
else{
cout << "Entered set_coefficient()" << endl;
while(start->degree != d && start->next != NULL){
cout << "Inside set_coefficient() while loop" << endl;
start = start->next;
}
if(c != 0 && start == 0)
start = new PolyNode(c,d,0);
else if(c!= 0 && start != 0)
start->coefficient = c;
else if(c == 0){
cout << "deleting a term" << endl;
delete start;
}
}
cout << "Leaving set_coefficient()" << endl;
}
ostream& operator<<(ostream& o,const Polynomial& p){
Polynomial::PolyNode* start = p.firstTerm;
for(unsigned int i = 0; start->next != 0; i++){
o << "Term " << i << "'s coefficient is: " << start->coefficient << " degree is: " << start->degree << endl << flush;
start = start->next;
}
return o;
}
Run Code Online (Sandbox Code Playgroud)
poly是一个指针,使用operator <<你需要说的自定义
cout << *poly; // output the object pointed-to, not the pointer itself
Run Code Online (Sandbox Code Playgroud)
你没有超载插入一个意味着什么Polynomial*.你也不应该试试.
除此之外,你可能应该通过const引用接受对象,没有理由让流输出操作符改变对象.