Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取对常量QString的引用_C++_Qt - Fatal编程技术网

C++ 获取对常量QString的引用

C++ 获取对常量QString的引用,c++,qt,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.

我试图在我的函数之外获取对
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. 
}
void函数(常量QString&a)
{
//代码
}
void otherFunction()
{

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

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

这是不可能直接实现的:在
function()
中,
a
参数的范围仅限于函数本身

您需要使用
常量QString&
参数扩展
其他函数
,并相应地调用它,或者将该值分配给
函数()
中的全局变量(通常不是首选方式),以便可以从
其他函数()
访问它:


只需将参数添加到
otherFunction()


你可以共享一个
静态常量QString&var;
,但这是一个低级趣味。你为什么要这样做?我相信你正在试图以一种复杂的方式实现某件事。试着在你需要的地方给出一个简短的例子。你甚至不知道这个函数是否是类的一部分。是的,这是一个要点,老兄-如果是我就更好了t;)很好,因此您可以按照我的建议将此变量定义为类成员。@Ash您作为类的公共成员的函数是一个非常重要的信息-您应该将其添加到问题中,我也编辑了我的示例。
static QString str;

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

void otherFunction() { 
    qDebug() << str;
}
class Sample {
   QString str;

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

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

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