[Qt-interest] Weird compiler error with QString(QChar(value))

Nikos Chantziaras realnc at arcor.de
Thu May 6 16:51:42 CEST 2010


On 05/06/2010 05:35 PM, Stephen Chu wrote:
> In article<201005052127.23761.thiago at kde.org>,
>   Thiago Macieira<thiago at kde.org>  wrote:
>
>> Em Quarta-feira 5. Maio 2010, às 20.51.00, Nikos Chantziaras escreveu:
>>> Not sure I understand why this won't compile:
>>>
>>>     int unicodeValue = func_that_returns_a_unicode_value();
>>>     QString s(QChar(unicodeValue));
>>>     const QByteArray&  utf8 = s.toUtf8();  //<-- error happens here
>>>
>>> I get:
>>>
>>> error: request for member 'toUtf8' in 's', which is of non-class type
>>> 'QString(QChar)'
>>>
>>> I'm confused as hell :P
>>
>> This is one of the things you just have to learn. This line:
>>
>>     QString s(QChar(unicodeValue));
>>
>> is not what you think.
>>
>> You thought you were declaring an object of class QString and calling one of
>> its constructors with a QChar (which in turn was initialised with an int).
>>
>> The compiler understood that you were declaring a pointer to a function that
>> returns QString and takes a QChar as a parameter.
>>
>> Solution:
>>
>>     QString s = QChar(unicodeValue);
>
> Thanks for the explanation. I ran into the same problem just last night.
> Pulling my hairs out on this one.
>
> One question though. If that line of code actually declares a function,
> what does 'unicodeValue' in the declaration do? I thought a function
> declaration is something like:
>
>      QString s(QChar unicodeValue);

It's the same since you can put parentheses pretty much everywhere.  As 
I posted previously for example, you can define main() like this:

   int main( int(argc), char**(argv) )

and it's accepted by the compiler.  That means that these two function 
declarations:

   QString s(QChar unicodeValue);
   QString s(QChar(unicodeValue));

are equivalent.  IMHO that's wrong, but then again, I don't know what 
would break in the C++ standard if it would treat it as wrong.  But 
given that C++ allows you to use simple types (int, char, etc) as classes:

   int i = int(50); //'int' is not a class, but you can use it as one

it should bark at the above definition of main().



More information about the Qt-interest-old mailing list