What if an argument has the same name as that of a data member?

偶尔善良 提交于 2020-01-16 09:59:38

问题


#include <iostream>

struct A
{
    A(int n) { std::cout << n; }
    int n{2};
};

int main()
{
    A a{1};
}

The output is 1 rather than 2.

Does the C++ standard define that the argument name is preferred if it is the same as that of a data member?


回答1:


The argument is in a "closer" scope than the member variable, so the argument shadows the member variable.

The obvious solution is to rename the argument (or the member variable), so they are not the same anymore.

You can also use this->n to explicitly use the member variable.



来源:https://stackoverflow.com/questions/59746542/what-if-an-argument-has-the-same-name-as-that-of-a-data-member

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