문제

I have code that supports both native C++ types as well as Qt types. For example there are string's and QString's which are "equivalent."

I have 2 functions, one that takes string's and one that takes QString's. The QString version converts the parameters to string's and then calls the string version of the function.

Here is some generic code of the problem:

int myClass::LoadQString(const QString &tagName, QString &toReturn)
{
    string tag = tagName.toStdString();
    string ret = toReturn.toStdString();
    //string& ret = toReturn.toStdString();    //This gives me an error

    return LoadString(tag, ret);
}

int myClass::LoadString(const string& tagName, string& toReturn)
{
    toReturn = "hello world!";

    ...
}

So, this code will compile and run...however, when I call LoadQString() the second parameter is an empty QString once it returns. You can see in my commented line where I tried string& ret = ... to get the reference to work. If I call LoadString() and then check the value of toReturn when it returns, it will be "hello world!" as expected.

Just trying to get the LoadQString() to work properly.

Thanks for all your help!

도움이 되었습니까?

해결책

You should convert from std::string back to QString after std::string version call

int myClass::LoadQString(const QString &tagName, QString &toReturn)
{
    string tag = tagName.toStdString();
    string ret = toReturn.toStdString();
    int retCode = LoadString(tag, ret);
    toReturn = QString::fromStdString(ret);
    return retCode;
}

다른 팁

You should call LoadString, not LoadXMLAttribute, and then assign ret to toReturn after you've called it, then return the int that LoadString returned.

First of all, toStdString creates an std::string object as a temporary. So naturally you cannot get a reference out of it, you must store the result in a value or extend its lifetime through a const reference.

However, for what you are doing, assuming toReturn is strictly an output parameter and that LoadString performs the actual work:

int myClass::LoadQString(const QString &tagName, QString &toReturn)
{
    string tag = tagName.toStdString();
    string ret;
    int result = LoadXMLAttribute(tag, ret);
    toReturn = QString::fromStdString(ret);
    return result;
}

If toReturn is not strictly an output parameter but also an input one (I recommend you avoid this as it's a rather confusing design practice):

int myClass::LoadQString(const QString &tagName, QString &toReturn)
{
    string tag = tagName.toStdString();
    string ret = toReturn.toStdString();
    int result = LoadXMLAttribute(tag, ret);
    toReturn = QString::fromStdString(ret);
    return result;
}

Pretty simple. Convert from QString to std::string, call your function which accepts std::strings, store return value, and convert the output parameter (ret) back to a QString assigned to your output parameter (toReturn).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top