问题
#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