问题描述
感谢您的建议我得到了Accelerated C ++我正在学习
它。我发现在运行时初始化常量
的可能性非常有趣,但看起来我没有把它弄好:
#include< iostream> ;
#include< string>
int main()
{
std: :字符串名称;
const std :: string store = name;
std :: cout<< Gimme a name << std :: endl;
std :: cin> name;
std :: cout<< 你写的 <<名称<< std :: endl;
std :: cout<< 商店被设置为 <<商店;
返回0;
}
输出结果为:
Gimme一个名字
Tom
你写了Tom
商店设置为
发生了什么商店的内容?谢谢,
问候,
deltaquattro
Hi,
thanks to your suggestions I got "Accelerated C++" and I''m studying
it. I found very interesting the possibility of initializing constants
at runtime, but it looks like I''m not getting it right:
#include <iostream>
#include <string>
int main ()
{
std::string name;
const std::string store = name;
std::cout << "Gimme a name " << std::endl;
std::cin >name;
std::cout << "You wrote " << name << std::endl;
std::cout << "Store was set to " << store;
return 0;
}
The output is:
Gimme a name
Tom
You wrote Tom
Store was set to
What happened to the content of store? Thanks,
greetings,
deltaquattro
推荐答案
什么内容?你复制了一个空字符串。
What content? You copied an empty string to it.
一个const的值只能设置一次,当它被声明时(const
类成员有点在这种情况下,你初始化
存储到name的值,当时恰好是空的。
移动行''const std :: string store = name;''down down''std :: cin
The value of a const can only be set once, when it''s declared (const
class members are a bit different) and in this case you initializes
store to the value of name, which happens to be empty at that moment.
Move the line ''const std::string store = name;'' down below ''std::cin
查看上面的代码,似乎你期望一个行为
类似于引用,其中store将是一个只读别名
的名字。要获得此行为,请将商店声明更改为
''const std :: string& store = name;''
-
Erik Wikstr?m
Looking at your code above it seems like you expect a behaviour
similar to that of references, where store would be a read-only alias
of name. To get this behaviour change the declaration of store to
''const std::string& store = name;''
--
Erik Wikstr?m
[..]
[..]
一个const的值只能设置一次,当它被声明时(const
类成员有点在这种情况下,你初始化
存储到name的值,当时恰好是空的。
移动行''const std :: string store = name;''低于''std :: cin
The value of a const can only be set once, when it''s declared (const
class members are a bit different) and in this case you initializes
store to the value of name, which happens to be empty at that moment.
Move the line ''const std::string store = name;'' down below ''std::cin
Erik,
语句。
Hi, Erik,
thank you very much for your useful answer. I''m not still used to the
fact that in C++ you can (in this case, you have to) place declaration
statements among executable statements.
是的,这就是我要找的东西:感谢您指点我/ b
引用,我不知道。
问候,
deltaquattro
Yes, that''s what I was looking for: thanks for pointing me to
references, which I didn''t know.
greetings,
deltaquattro
这篇关于初始化const的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!