Correct C pointer notation [closed]

2020-05-02 09:01发布

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

4条回答
老娘就宠你
2楼-- · 2020-05-02 09:25

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

Or is that const string &str ? Hmm.

倾城 Initia
3楼-- · 2020-05-02 09:32

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.

仙女界的扛把子
4楼-- · 2020-05-02 09:37

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;
查看更多
再贱就再见
5楼-- · 2020-05-02 09:46

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;
查看更多
登录 后发表回答