PDA

View Full Version : Overloading + operator in QString



harvey_slash
16th October 2013, 13:31
I want to overload the + operator for my mainwindow class(or any other class) for Qstring. this is what I have done so far :

QString operator+(QString a,QString b)
{
qDebug()<<"works";
}

but the thing is, the QString + operator is already overloaded(to concatenate, I guess). so, if I use the above code, it results in ambiguity(both the signatures are same). how do I override the actual function to my own function without making a new class to hold QString?

stampede
16th October 2013, 14:20
Why ? What do you expect to get with for example "x" + "y" other than "xy" ?
If you need custom behaviour just use custom methods, like
QString myPlus(const QString& a, const QString& b).
You cannot provide new declarations for functions / classes etc. that are already defined.
If you really want, you can implement the operator+ as a member method of your class, like:


class Test{
public:
Test(const QString& s){
buff = s;
}
QString operator+(const QString& s){
return buff+s;
}
private:
QString buff;
};

int main(int argc, char ** argv)
{
Test t("x");
qDebug() << t+"y";
return 0;
}

or as non-member function and make it a "friend" of the class...
I don't know, personally I just avoid overloading operators.

Btw. It is never a good idea to modify something that is well defined. This is probably your personal project, but imagine that someone will someday work on this code, he'd be very surprised to find that "newString = string1+string2" is not really what its supposed to be, or have a nasty side effects...