Correct C pointer notation [closed]

主宰稳场 提交于 2019-12-20 05:47:14

问题


Which one is the best way to write:

string* str

Or:

string *str

Is there any drawback of side effect to one of them ?

Thanks


回答1:


A reason to prefer the second one is when you declare multiple variables at once:

string *str, *foo;
string* str, foo;

Those two lines are different, the first one declares to pointers, whereas the second one declares one pointer to string and one string.

[Comment by FredOverflow] This problem can be solved by some template magic, though ;-)

template <typename T>
struct multiple
{
    typedef T variables;
};

multiple<string*>::variables str, foo;



回答2:


Although I prefer the first one there is a reason to prefer the second, consider:

string* str, a;
string *str, a;

In the last case it is clear that * applies only to str. However using such declarations is often considered a bad style.




回答3:


I do it like this:

string *str;

Because it makes a difference when you do this

string *str, *str2;

You could also do

typedef string* stringPtr;

So that you could do

stringPtr str, str2;



回答4:


In C++ - neither - this should be const string& str.

Or is that const string &str ? Hmm.



来源:https://stackoverflow.com/questions/4071068/correct-c-pointer-notation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!