获取const QString的引用

时间:2013-01-25 11:38:03

标签: c++ qt

我试图在我的功能之外引用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的引用?

3 个答案:

答案 0 :(得分: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; }
};

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

只需将参数添加到otherFunction()

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

void otherFunction(const QString &a)
{
    //code
    //do stuff with a
}
相关问题