Comp Sci (C++) Not sure what the problem wants me to do.

  • Thread starter Thread starter cpponyou
  • Start date Start date
AI Thread Summary
The homework problem requires creating an overload of the << operator for a class hierarchy with a virtual method print. The goal is to enable the expression out << p to call p.print() automatically, where p is an object of the class. It's important to ensure that the overloaded operator adheres to the standard semantics of the << operator, allowing for chaining with other output, such as strings. This means that the implementation should support expressions like out << "Members of p:\n" << p << "\nMembers of q:\n" << q. The key takeaway is to focus on overriding operator<< to integrate with the existing print method.
cpponyou
Messages
1
Reaction score
0
I have this HW problem, but I cannot figure out what it wants me to do. I don't want anyone to solve it for me, just point me in the right direction.

Suppose that a class hierarchy has a virtual method print
Code:
class C {
virtual void print( ostream& ) const;
};

that outputs C's members to the stream ostream. Write one overload of << so that the statement

Code:
out << p;

outputs p's members to the stream out, where p is any object that belongs to a class in the hierarchy.

What I don't understand is the out << p bit. Am I supposed to be able to do

Code:
out << p;

in my main() and have the overload call p.print() ?
 
Physics news on Phys.org
That is exactly what you are supposed to do.

You should probably make your overloaded function obey the semantics of the << operator as used with streams so that given two such objects p and q the following works:
Code:
out << "Members of p:\n" << p << "\nMembers of q:\n" << q;
 
Last edited:
Indeed. So they want you to override operator<<
 
Thread 'Have I solved this structural engineering equation correctly?'
Hi all, I have a structural engineering book from 1979. I am trying to follow it as best as I can. I have come to a formula that calculates the rotations in radians at the rigid joint that requires an iterative procedure. This equation comes in the form of: $$ x_i = \frac {Q_ih_i + Q_{i+1}h_{i+1}}{4K} + \frac {C}{K}x_{i-1} + \frac {C}{K}x_{i+1} $$ Where: ## Q ## is the horizontal storey shear ## h ## is the storey height ## K = (6G_i + C_i + C_{i+1}) ## ## G = \frac {I_g}{h} ## ## C...

Similar threads

Replies
2
Views
2K
Replies
2
Views
5K
Replies
1
Views
1K
Replies
12
Views
2K
Replies
7
Views
2K
Replies
15
Views
2K
Replies
5
Views
2K
Replies
1
Views
2K
Back
Top