C ++空String构造函数 [英] C++ empty String constructor

查看:230
本文介绍了C ++空String构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个C ++初学者,很抱歉,如果这个问题太基本了。

I am a C++ beginner, so sorry if the question is too basic.

我试图收集字符串constrcturs并尝试所有的)。

I have tried to collect the string constrcturs and try all them out (to remember them).

string strA();          // string(); empty string // incorrect
string strB("Hello");   // string( const char* str)
string strC("Hello",3); // string( const char* str, size_type length)
string strD(2,'c');     // string( size_type lenght, const char &c)
string strE(strB);      // string( const string& s)

cout << strA << endl;
cout << strB << endl;
cout << strC << endl;
cout << strD << endl;
cout << strE << endl;

除了 strA ,所有这些都有效。打印1。 为什么?在这种情况下,strA的类型是什么?如果我不确定,我如何检查类型的东西?

All of them works except for the strA. It prints "1". Why? Whats the type of the strA in this case? How can I check the type of stuff when I am unsure?

我注意到正确的方式是这(这似乎是不一致与其他构造函数,有时括号有时没有括号):

I have noticed that the correct way is this (which by the way seems to be inconsistent with the other constructors, sometimes parens sometimes no parens):

string strA;

ps:粗体的问题,通常不相关的答案将被拒绝。

ps: question in bold, usual irrelevant answers will be downvoted.

推荐答案

这是一个非常受欢迎的getcha。 C ++语法是模糊的。解决歧义的规则之一是如果某事看起来像声明它是一个声明。在这种情况下,不是定义一个变量,而是声明一个函数原型。

This is a very popular gotcha. C++ grammar is ambiguous. One of the rules to resolve ambiguities is "if something looks like declaration it is a declaration". In this case instead of defining a variable you declared a function prototype.

string strA();

相当于

string strA(void);

一个返回字符串的非arg函数的原型。

a prototype of a no-arg function which returns string.

如果你想显式调用无参构造函数,请尝试:

If you wish to explicitly call no-arg constructor try this:

string strA=string();

它不完全等效 - 这意味着'使用no-arg构造函数创建一个临时字符串,然后复制它以初始化变量strA',但允许编译器优化它并省略复制。

It isn't fully equivalent - it means 'create a temporary string using no-arg constructor and then copy it to initialize variable strA', but the compiler is allowed to optimize it and omit copying.

编辑:
这是C ++常见问题解答Lite 中的相应项目

这篇关于C ++空String构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆