0

const QString &a関数の外部への参照を取得しようとしています。

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. 
}

への参照を取得するにはどうすればよいaですotherFunctionか?

4

3 に答える 3

2

これを直接行うことはできません。 では、パラメーターfunction()スコープaは関数自体に限定されます。

からアクセスできるように、パラメータを使用して拡張otherFunctionし、const QString&それに応じて呼び出すか、値を 内のグローバル変数に割り当てる必要があります (通常は推奨される方法ではありません) 。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; }
};
于 2013-01-25T11:40:32.920 に答える
0

にパラメータを追加するだけotherFunction()です:

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

void otherFunction(const QString &a)
{
    //code
    //do stuff with a
}
于 2013-01-25T11:44:18.630 に答える
0

たとえば、 QString a をクラスメンバーとして定義できます:)したがって、クラスの任意のメソッドからこの変数にアクセスできます。

classMyCoolClass
{
public:
  void function();
  void otherFunction();    
private:
   QString a;
};
于 2013-01-25T11:40:17.573 に答える