开发者

C++ Class Templates (Queue of a class)

Ok, so I have my basic linked Queue class with basic functions such as front(), empty() etc.. and I have transformed it into a template. Now, I also have a class called Student. Which holds 2 values: Student name and Student Id. I can print out a student with the following code..

Student me("My Name", 2);
cout << me << endl; 

Here is my display function for student:

void display(ostrea开发者_Python百科m &out) const { 
 out << "Student Name: " << name << "\tStudent Id: " << id
     << "\tAddress: " << this << endl;  
} 

Now it works fine, you can see the basic output. Now I'm declaring a queue like so..

Queue<Student> qstu; 

Storing data in this queue is fine, I can add new values and such.. now what I'm trying to do is print out my whole queue of students with:

cout << qstu << endl; 

But its simply returning an address.. here is my display function for queues.

void display(ostream & out) const {
 NodePointer ptr; 
 ptr = myFront; 

 while(ptr != NULL) { 
  out << ptr->data << " "; 
  ptr = ptr->next; 
 } 
 out << endl; 
}

Now, based on this, I assume ptr->data is a Student type and I would assume this would work, but it doesn't. Is there something I'm missing? Also, when I Try:

ptr->data.display(out); 

(Making the assumtion ptr->data is of type student, it does not work which tells me I am doing something wrong.

Help on this would be much appreciated!


Based on the code you show here, the following does not work:

Student me("My Name", 2);
cout << me << endl; 

If you want to be able to insert something into a stream like that, you need to overload operator<< for the type of ptr->data. The declaration of such an overloaded operator would look like

std::ostream& operator<<(std::ostream& o, const Student& s);

If ptr->data is a pointer, then you need to dereference it before inserting it into the stream:

cout << *ptr->data;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜