在类声明之前调用一个类的成员函数
我正在类声明之前定义一个宏。该宏调用该类的成员函数。我的示例代码如下。在类声明之前调用一个类的成员函数
样品类的声明,
// 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.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.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;
}
当我运行main.cpp中,我得到一个错误宏定义中的sample.h文件:“Sample”不是类或名称空间名称。
如何在类的范围之外和类声明之前调用类的成员函数?我对编程颇为陌生,您的反馈会帮助我,谢谢。
如果你想有一个宏跨越多行,你必须把\
在每行的末尾:
#define CALCULATETEMP(a, b, c) { \
int d = Sample::getTempIncrement(a,b,c); \
stringstream ss; \
ss << d; \
cout << ss.str() << endl; \
}
而且,你为什么不只是使用功能为这个(而不是使用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;
}
您已经定义通过与{
预处理器置换,然后用一束全球空间编码,这是相当不合法的跟着它。
我建议回到关于预处理器宏的教程和/或阅读内联函数。
谢谢。你能否给我一些关于全球空间编码的信息,我没有得到这个术语。 –
@capricorn_heitus他意味着因为宏只在第一行,所以编译器会认为你试图在一个函数之外进行计算(在文件的_top-level_处,就像你可以在Python或其他软件中做的那样)你不能在C++中完成。那和你有一个流浪的'}'。 –
@SethCarnegie谢谢,我现在明白了。所以,解决这个问题的方法就是使用'\'将多个宏跨越宏,这使得宏定义中的计算成为可能,对吗? –
我相信还有另外一个问题。 Sample :: getTempIncrement()没有声明为静态,所以你需要在宏中有一个Sample实例。
好的,+1。 –
是的,'stringstream'在那里有一些开销,谢谢。我只是在尝试宏,没有具体说明不用函数做它。 –
@capricorn_heitus好吧,试验没有错:)我只是想指出它的情况下,这是真正的代码的地方。 –
请记住,不要在'\'之后留下任何空格,否则最终会出现同样的问题。它将逃离空间而不是任何换行。 –