繁体   English   中英

在参数化构造函数中使用 this 指针

[英]Using this pointer in parameterized constructor

当我将参数传递给构造函数并在主体内进行赋值时,我必须使用这个指针,否则它不会运行。

class Employee
{
    public:
        string name;
        const char *id;
        int age;
        long salary;


        Employee (string name,const char* id, int age, long salary)   
        {
            this->name = name;
            this->id = id;
            this->age = age;
            this->salary = salary;
        };
};

但如果我使用其他方法,则不需要这个指针。 为什么会这样?

Employee(string name,const char id[], int age, long salary): name(name),id(id),age(age),salary(salary)
         {};

因为名字有冲突。 如果您在示例中编写name = name ,则将局部变量name分配给自身。

通过使用this ,您明确地引用了您的 object,因此明确地引用了您想要分配name成员的 state。

初始化列表有效,因为只有成员可以出现在其中。 但是考虑一下当您(假设地)想要使用成员name初始化成员id (忽略参数)时会发生什么。 在这种情况下, this->name再次成为必需品。

可以通过以不同方式命名成员或 arguments 来规避整个问题,例如m_是一个通用约定: m_name = name

在第一个中,构造函数的参数会影响 class 的字段。 您需要this->来指定将值分配给哪个变量。 在第二个中,您使用初始化列表。 (阅读此处了解更多信息: https://isocpp.org/wiki/faq/ctors#init-lists

对于第一种情况,在构造函数主体中,非限定名称总是在构造函数 scope 中找到,并引用构造函数参数。 然后 名称查找停止,进一步的 scope 包括 class scope 将不会被检查。 然后,当您要指定数据成员时,您必须像this->name那样明确限定,否则, name = name; 意味着自己分配name

对于第二种情况,数据成员由成员初始化列表初始化(顺便说一句,这不是第一种情况的赋值)。 [class.base.init]/2

(强调我的)

In a mem-initializer-id an initial unqualified identifier is looked up in the scope of the constructor's class and, if not found in that scope, it is looked up in the scope containing the constructor's definition. [ Note: If the constructor's class contains a member with the same name as a direct or virtual base class of the class, a mem-initializer-id naming the member or base class and composed of a single identifier refers to the class member. 可以使用限定名称指定隐藏基 class 的 mem-initializer-id。 — end note ]除非 mem-initializer-id 将构造函数的 class 命名为构造函数的 class 的非静态数据成员,或者该 class 的直接或虚拟基数,否则构成 mem-D61

这意味着,mem-initializer-id 将在 class 的 scope 中查找,它不会也不能引用构造函数参数。

另一方面, [class.base.init]/15

mem-initializer 的 expression-list 或 braced-init-list 中的名称在为其指定 mem-initializer 的构造函数的 scope 中进行评估。

在构造函数的 scope 中查找初始化表达式中的名称,然后找到构造函数参数。 所以name(name)表示通过构造函数参数name初始化数据成员name

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM