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
}