如果参数与数据成员具有相同的名称怎么办? [英] What if an argument has the same name as that of a data member?

查看:114
本文介绍了如果参数与数据成员具有相同的名称怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

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

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

输出为1而不是2.

如果与数据成员的名称相同,C ++标准是否定义了首选的名称?

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

推荐答案

自变量位于比成员变量更近"的范围内,因此自变量 shadows 属于成员变量.

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.

您还可以使用this->n显式使用成员变量.

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

这篇关于如果参数与数据成员具有相同的名称怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆