2011-06-18 192 views
4

所以我不知道为什么我的插入操作符不适用于我的列表类。我已经看了一会儿,我认为超载的语法是正确的。不确定在这一个。任何暗示,为什么它不工作?这里的代码:重载<<插入操作符无法正常工作

编辑:改变了一些代码,以目前它是什么。

对不起,现在特别是现在的问题是,我无法打印任何东西,简单的打印和空行。

这里的司机:

#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; 
} 

这里的标题:

#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 

这里的实现:

#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; 
} 
+2

“这不工作”不是一个有效的问题描述。它编译失败吗?它在运行时崩溃吗?它运行没有崩溃,但产生意想不到的结果?尝试在发布问题时添加那种信息。我也推荐阅读[写完美的问题](http://tinyurl.com/so-hints) –

+0

@Martinho Fernandes这是当我在主要方法中使用插入。它应该打印列表中列出的两个术语的数据,而是打印出一个内存地址。 –

+1

@Keoki Zee。我会给你一个:) –

回答

5

poly是一个指针,使用自定义operator <<你需要说

cout << *poly; // output the object pointed-to, not the pointer itself 

您还没有重载插入Polynomial*的含义。你也不应该尝试。

除此之外,你可能应该接受const引用的对象,没有理由让流输出操作符去改变对象。