Reputation: 73
I am defining a macro before a class declaration. The macro calls a member function of the class. My sample code is below.
Sample class declaration,
// sample.h
#include <sstream>
#include <iostream>
using namespace std;
#define CALCULATETEMP(a, b, c) {
int d = Sample::getTempIncrement(a,b,c);
stringstream ss;
ss << d;
cout << ss.str() << endl;
}
class Sample {
public:
Sample();
int getTempIncrement(int a, int b, int c);
~Sample();
};
Sample class implementation,
//sample.cpp
#include "sample.h"
Sample::Sample() {
}
int Sample::getTempIncrement(int a, int b, int c) {
int temp = 5;
int d = (a*temp) + (b+c)*temp;
return d;
}
Sample::~Sample() {
}
Main routine,
//main.cpp
#include "sample.h"
int main(int argc, char* argv[]) {
int a = 1;
int b = 2;
int c = 3;
CALCULATETEMP(a, b, c);
return 0;
}
When I run the main.cpp, I am getting an error in sample.h file within the macro definition: "Sample" is not a class or namespace name.
How can I call a member function of the class outside the scope of the class and before the class declaration? I am quite new to programming, your feedback would help me, Thanks.
Upvotes: 2
Views: 1225
Reputation: 1467
I believe there's another problem, as well. Sample::getTempIncrement() isn't declared as a static, so you'll need a Sample instance available in the macro.
Upvotes: 2
Reputation: 40859
You've defined CALCULATETEMP(a,b,c)
to be replaced by the preprocessor with {
and then followed it with a bunch of global space coding, which is quite illegal.
I would suggest going back to the tutorial on preprocessor macros and/or reading up on inline functions.
Upvotes: 0
Reputation: 75130
If you want a macro to span multiple lines, you have to put \
at the end of each line:
#define CALCULATETEMP(a, b, c) { \
int d = Sample::getTempIncrement(a,b,c); \
stringstream ss; \
ss << d; \
cout << ss.str() << endl; \
}
Also, why don't you just use a function for this (and not use stringstream
)?
class Sample {
public:
Sample();
int getTempIncrement(int a, int b, int c);
~Sample();
};
void calctemp(int a, int b, int c) {
int d = Sample::getTempIncrement(a,b,c);
stringstream ss;
ss << d;
cout << ss.str() << endl; // why are you using stringstream? It could be
// just cout << d << endl;
}
Upvotes: 4