I'm getting really close to the end of the C++ tutorial, but I'm having problems using Classes and Functions.
What I have is a function which for this example is this:
1 2 3 4 5 6
void subtraction (ex1, ex2) {
int a, b;
a = ex1.num;
b = ex2.num;
a -= b;
return a; }
where ex1 and ex2 are classes each with an integer called num. These integers are public.
The problem is that when I compile the code, there is an error with the code
1 2
a = ex1.num;
b = ex2.num;
The problem, as stated by the compiler is: expected primary-expression before '.' token
I'm getting really close to the end of the C++ tutorial, but I'm having problems using Classes and Functions.
What I have is a function which for this example is this:
1
2
3
4
5
6
void subtraction (ex1, ex2) {
int a, b;
a = ex1.num;
b = ex2.num;
a -= b;
return a; }
where ex1 and ex2 are classes each with an integer called num. These integers are public.
The problem is that when I compile the code, there is an error with the code
1
2
a = ex1.num;
b = ex2.num;
The problem, as stated by the compiler is:
expected primary-expression before '.' token
Thanks in advance to anybody wiling to help!
You must show the data types of ex1 and ex2. You mention pointers, so if these are pointers, you must use operator-> instead.
#include <iostream>
usingnamespace std;
class ex1 {
public:
int num;
}exmpl1;
class ex2 {
public:
int num;
}exmpl2;
int subtraction (ex1, ex2) {
int a, b;
a = ex1.num;
b = ex2.num;
a -= b; }
int main () {
int a;
exmpl1.num = 10;
exmpl2.num = 5;
a = subtraction (exmpl1, exmpl2); }
It would be easier for me to see what you did if you just take it and edit it to work properly, and obviously, explain what you did.
Your subtraction function is incorrectly written. It has to be something like this:
1 2 3 4 5 6 7 8
int subtraction (ex1 theFirstObject, ex2 theSecondObject) {
int a, b;
a = theFirstObject.num;
b = theSecondObject.num;
a -= b;
//You forgot this line:
return a;
}
But even better would be to pass those by const reference.