2013-01-03 69 views
3
#include <cstdlib> 
#include <iostream> 
#include "Node.h" 
#ifndef HW4_H 
#define HW4_H 
using namespace std; 
/** 
You are to implement the two functions in this class. 
You can add any other method or members to it as well. 
However, you cannot change their signature. 
**/ 
class HW4{ 

public: 
    int count(Node* r) const 
    { 
     if(r->next==NULL&&r->bro==NULL) { return 0;} 
     if(r.isLeaf()) 
     { 
      return ((1+count(r->next)+count(r->bro))); 
     } 
     count(r->next); 
    } 

    /* 
    This method will return true if the tree rooted at node sn can answer 
    the demand induced by its leaves. 
    */ 
    bool canDemandBeAnswered(Node* root) 
    { 
     if(count(root)>(root.getCapacity())) 
     { 
      return 0; 
      exit(0);  
     } 
     else 
     { 
      return (canDemandBeAnswered(root->next)&&canDemandBeAnswered(root->bro)); 
     } 
    } 




    /* 
    This method should return a linked list of nodes representing the 
    customers with the overall highest revenue. 
    The resulting list should conform to the capacity limitations. 
    */ 
    //  Node* getBestCustomers(Node* root); 


}; 

#endif 

#include <cstdlib> 
#ifndef NODE_H 
#define NODE_H 

/** 
The Node class. You must implement the two methods isLeaf() and addChild(Node*) below. 
Otherwise, you can add any methods or members your heart's desire. 
The only limitation is that they have to be in this file. 
**/ 
class Node { 
private: 
    int capacity; 
    int price; 


public: 
    /** 
    Hint: to be used for saving the Node's children and for returning the linked list   
    **/ 
    Node* next; 
    Node* bro; 

    Node(){ 
     capacity = 0;   
     price = 0; 
    } 
    Node(int capacity_){ 
     capacity = capacity_; 
     price = 0; 
    }     

    //should return true if this node has no children, false otherwise. 

    //this method adds a child to this node. 


    int getCapacity(){ 
     return capacity; 
    } 


    int getPrice(){ 
     return price; 
    } 

    void setPrice(int price_){ 
     price = price_; 
    } 


    bool isLeaf() 
    { 
     if((this->next)->capacity==0) 
      return 1; 
     else return 0; 
    }  


    void addChild(Node* child) 
    { 
     Node* temp; 
     if(this->next!=NULL) 
     { 
      temp=this->next; 
      child->bro=temp; 
      this->next=child; 
     } 
     else 
      this->next=child; 
    } 
}; 




#endif 

我收到以下錯誤:「isLeaf()尚未聲明」。我不明白爲什麼 - 我宣佈了兩個。C++編譯器錯誤:「isLeaf()尚未聲明」 - 但它是

回答

7
bool canDemandBeAnswered(Node* root) 
{ 
    if(count(root)>(root.getCapacity())) 

這試圖調用getCapacity上Node *。但Node *不具有稱爲getCapacity的功能 - Node。您可以使用(*root).getCapacity()或簡寫形式root->getCapacity()

 if(r.isLeaf()) 

您在這裏遇到同樣的問題。 rNode *

3

Did you mean r->isLeaf()而不是r.isLeaf(),因爲r是一個指針嗎?

+0

dunno。對於我看到的r.isLeaf()也必須給出編譯器錯誤。 – Stefan

3

您應該使用->而不是.來訪問這些功能,因爲r是一個指針。

3

成員訪問指針是不同的。您必須使用間接運算符->。這些不是實際的對象,而只是指向它們的指針。