名称隐藏在构造函数初始化列表中

JBe*_*ley 4 c++ constructor initialization this name-hiding

我想修改构造函数以使用初始化列表,如下例所示:

class Foo
{
public:
   Foo(std::wstring bar);
private:
   std::wstring bar;
};

// VERSION 1:

Foo::Foo(std::wstring bar) {this->bar = bar}

// VERSION 2:

Foo::Foo(std::wstring bar) : this->bar(bar) {} // ERROR!
Run Code Online (Sandbox Code Playgroud)

不幸的是我不能做版本2,因为你不能使用this数据成员的指针,因为(我猜)它们当时还不存在。那么,我该如何处理名称隐藏问题(即我的参数和我的数据成员具有相同的名称)?

Jos*_*eld 5

你不需要。第一个bar将引用成员,第二个bar将引用参数:

Foo::Foo(std::wstring bar) : bar(bar) {}
Run Code Online (Sandbox Code Playgroud)