-
help with program!
I need this program to display the output (" 111 56 "). Whats the problem with it?
Code:
#include <iostream.h>
class Exchg {
public:
void exchange (int& a, int& b) {
int temp = a;
a = b;
b = temp;}};
main () {
int num1 = 56;
int num2 = 111;
cout << "the two numbers: " << num1 << "," << num2 << "..." << endl;
exchange (num1, num2);
cout << "... are now exchanged: " << num1 << "," << num2 << endl;
}
thanks!:confused:
-
don't you need to intz the class within main() before you call it. i really have no idea though, i just started classes yesterday/today
-
try
Code:
int main()
{
code here...
return 0;
}
I'm not sure you want a class to do the exchange, though. Classes are used to represent objects. It may work, never tried it, but normally you'd just use a function to do this.
-
You need to create an instance of your class for the methods to work properly:
Code:
#include <iostream.h>
class Exchg
{
public:
void exchange (int& a, int& b) {
int temp = a;
a = b;
b = temp;
}
};
int main ()
{
Exchg e;
int num1 = 56;
int num2 = 111;
cout << "the two numbers: " << num1 << "," << num2 << "..." << endl;
e.exchange (num1, num2);
cout << "... are now exchanged: " << num1 << "," << num2 << endl;
return 0;
}
Or you could declare exchange as being static and instead of creating an instance of the class, just use the scope resolution operator on the class itself:
Exchg::exchange (num1, num2);
On a side note, what is this?
>b = temp;}};
I see it everyone once and a while, is it an actual style or just someone wanting to make code harder to read? If it's the former I highly recommend not using it, it looks too much like a syntax error for my comfort. Especially when taken out of context.
-Prelude
-
i'll try to do that, but im using a book to learn c++ and it is very good, it leaves out stuff all the time, grrrr...:mad:
-
sometimes books purposefully do that, to show you the errors, and then build it up over time, to a working program. It usually shows common errors, that people make. Some books.....
-
>but im using a book to learn c++ and it is very good, it leaves out stuff all the time, grrrr...
Somehow I ask the question, if this book leaves important info out all the time, is it really a good book?
>sometimes books purposefully do that
Perhaps using something and not explaining it until later when the reader would understand, or showing what not to do. But even progressively complex programs should compile and run properly in every phase.
-Prelude
-
the series of books we are using for my computer science class, sometimes it makes purposeful errors (it tells you theres going to be an error), so the students sees what the next program improves upon and corrects.