C++ Typedef 中的指针
我对 C++ 比较陌生,我首先阅读 C++ Primer 第四版 。它有一个部分解释了指针和 Typedef,从以下代码开始。
typedef string *pstring;
const pstring cstr;
我知道在定义 typedef string *pstring;
后,我可以使用 *pstring
在我的代码中声明字符串变量。
*pstring 值1; // 这两行是相同的,
字符串值2; // value 1 和 value2 are string
本书继续 const pstring cstr1;
和 *const string cstr2;
是相同的。我不明白为什么他们有相同的声明?
I'm relatively new to C++, I start by reading C++ Primer 4th edition. It has a section explains about Pointers and Typedefs, start with bellowing code.
typedef string *pstring;
const pstring cstr;
I know that after I define typedef string *pstring;
I can use *pstring
to declare string variable in my code.
*pstring value1; // both of these line are identical,
string value2; // value 1 and value2 are string
The book continue with const pstring cstr1;
and *const string cstr2;
are identical. I don't understand why they're same declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们并不相同。
They are not identical.
我真的希望你引用的那本书不像你的引文看起来那么不准确。我确信你没有准确地引用它。请回去将书上的内容(我没有副本)与您所写的内容进行比较。
鉴于:
你写的
和
是相同的。事实上,两者都是无效的。
如果你声明了一些
const
,你需要为其提供一个初始值。而*const string cstr2;
的语法是错误的。因此,正确的方法是:
cstr1
和cstr2
都是指向字符串的 const(即只读)指针。请注意,
const
关键字必须位于*
之后,因为我们需要一个指向字符串的 const 指针,而不是指向 const 字符串的指针。但无论如何,为指针类型声明 typedef 通常不是一个好主意。类型是指针类型这一事实几乎影响您使用它所做的一切;为它创建一个 typedef 隐藏了这个事实。
I really hope the book you're quoting isn't as inaccurate as your quotations make it seem. I feel sure that you haven't quoted it accurately. Please go back and compare what's in the book (I don't have a copy) to what you've written.
Given:
You write that
and
are identical. In fact, both are invalid.
If you declare something
const
, you need to provide an initial value for it. And the syntax of*const string cstr2;
is just wrong.So here's a correct way to do it:
Both
cstr1
andcstr2
are const (i.e., read-only) pointers to string.Note that the
const
keyword has to be after the*
, because we want a const pointer to string, not a pointer to const string.But in any case, declaring a typedef for a pointer type is usually a bad idea. The fact that a type is a pointer type affects almost everything you do with it; making a typedef for it hides that fact.
很高兴您能够了解 typedef,但就个人而言,当您在应用程序中看到一万个 typedef 以及数百万行代码时,那么...... typedef 就失去了光彩。然后它们只会混淆真正的代码。我发誓,我维护的一些代码的开发人员喝了 typedef 的酷帮助,并将它们用于一切!
我看到的唯一好处是使用它们来缩短很长的键入名称。例如与 STL 一起使用的长类型。
It's great that you are learning about typedefs, but personally when you see ten thousand of them in your application with millions of lines of code, then.... typedefs lose their luster. They then only serve to obsfucate the real code. I swear some devs whose code I've maintained drank the typedef cool aid and use them for everything!
The only benefit I've seen is to use them to shorten very long typed names. such as long types used with the STL.