2013-01-25 57 views
0

我試圖得到一個參考const QString &a超出了我的功能即獲取引用爲const QString的

void function(const QString &a) 
{ 
    //code 
} 

void otherFunction() 
{ 
    // code <<<<< 
    // I'm unsure how I would be able to get a reference to 
    // const QString &a here and use it. 
} 

我怎麼能得到otherFunctiona參考?

classMyCoolClass 
{ 
public: 
    void function(); 
    void otherFunction();     
private: 
    QString a; 
}; 
+0

你可以分享'靜態常量QString的& var;'但就是口感不佳。 –

+4

_你爲什麼想這樣做?我相信你正試圖以一種複雜的方式實現某些目標。嘗試提供一個簡短的例子,你需要這個。 – Zeta

回答

0

例如,你可以定義一個QString的作爲類成員:) 所以,你可以從你的類中的任何方法來訪問這個變量function(),在範圍a參數的僅限於函數本身。

您可能需要與const QString&參數延伸otherFunction並相應地調用它,或值分配給一個全局變量(通常不是優選的方式)的內部function(),以便它可以從otherFunction()進行訪問:

static QString str; 

void function(const QString& a) { 
    str = a; 
} 

void otherFunction() { 
    qDebug() << str; 
} 

既然你標記這個問題與C++,首選的方法是創建一個類的成員,其持有QString

class Sample { 
    QString str; 

public: 
    void function(const QString& a) { str = a; } 

    void otherFunction() { qDebug() << str; } 
}; 
+0

你甚至不知道這個函數是否是類的一部分。 – Zeta

+0

是的,這是一個觀點,夥計 - 它會更好一些;) – duDE

+0

函數'void function'是類的一部分,它是公開的。 – Ash

2

直接是不可能的:

0

只是一個參數添加到otherFunction()

void function(const QString &a) 
{ 
    //code 
    otherFunction(a); 
} 

void otherFunction(const QString &a) 
{ 
    //code 
    //do stuff with a 
}