Вопрос

So I can't figure out why my insertion operator isn't working for my list class. I've looked at it for a while and I think the syntax is correct for overloading. Not sure on this one. Any hints as to why it's not working?? Here's the code:

EDIT:Changed some code around to what it currently is right now.

Sorry, the problem specifically now is that I cannot get it to print anything out, it simple prints and empty line.

here's the driver:

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

Here's the header:

#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

Here's the implementation:

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

Нет правильного решения

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top