[英]& symbol in C++ preprocessor
那里。 我對C ++ #define語句中的類名和變量名之間的&符號的用法感到困惑。
我在xbmc源代碼的globalhandling.hpp文件中找到了它,以創建一個全局單例。
我寫了一個類似版本的代碼片段來弄清楚它的作用。 我在試驗中發現的是,僅在使用&時調用了一個構造函數和析構函數。 如果我忽略它,則調用一個構造函數和兩個析構函數。
在這種情況下,&是按位運算符還是地址運算符?
#include <iostream>
#include <boost/shared_ptr.hpp>
using namespace std;
class aClass
{
public:
aClass() { cout << "Constructor\n"; }
aClass getInstance() { return *this; }
void printMessage() { cout << "Hello\n"; }
~aClass() { cout << "Destructor\n"; }
};
#define GLOBAL_REF(classname,variable) \
static boost::shared_ptr<classname> variable##Ref(new classname)
#define GLOBAL(classname,variable) \
GLOBAL_REF(classname,variable); \
static classname & variable = (*(variable##Ref.get()))
GLOBAL(aClass,aVariable);
int main()
{
aVariable.printMessage();
return 0;
}
您所指的&
符號大概是這個:
static classname & variable = (*(variable##Ref.get()))
在這種情況下,&符與C預處理器無關,實際上是C ++ 參考符號 。
通常,您將使用它來引用已聲明的對象,類似於指針。
例如:
int a = 1;
int b = a;
int &c = a;
// a = 1, b = 1, c = 1.
b = 2;
// a = 1, b = 2, c = 1.
a = 3;
// a = 3, b = 2, c = 3. Note that variable 'c', which is a reference to 'a', has also changed.
c = 4;
// a = 4, b = 2, c = 4.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.