开发者

C++ Class Templates (Queue of a class)

开发者 https://www.devze.com 2022-12-25 23:45 出处:网络
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:

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

精彩评论

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

关注公众号