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

我怎样才能获得对ain的引用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

例如,您可以将 QString a 定义为类成员:) 因此您可以从类的任何方法访问此变量:

classMyCoolClass
{
public:
  void function();
  void otherFunction();    
private:
   QString a;
};
于 2013-01-25T11:40:17.573 回答
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 回答