使用其中的部分(对应于基类)初始化成员

Using parts of this (corresponding to base-class) to initialize a member

本文关键字:于基类 基类 成员 初始化      更新时间:2024-05-10

背景:我有这样的东西(但Z中的重要代码我不想更改,并且警告是全局启用的——我知道我可以禁用它(:

#pragma warning (error: 4355)
struct A;
struct B;
struct MapCompare {
A*the;
MapCompare(A*a):the(a) {;}
bool operator()(int,int) const;
};
class Z {
A a;
B b;
std::map<int,int,MapCompare> m;
public:
Z():m{MapCompare{&a}} {;}
...
};

但我想更改为在MapCompare中同时使用a和b。影响较小的变体似乎是:

#pragma warning (error: 4355)
struct A;
struct B;
struct AB {
A a;
B b;
};
struct MapCompare {
AB*the;
MapCompare(AB*ab):the(ab) {;}
bool operator()(int,int) const;
};
class Z : public AB {
std::map<int,int,MapCompare> m;
public:
Z():m{MapCompare{static_cast<AB*>(this)}} {;}
...
};

错误消息为:

错误C4355:"this":在基成员初始值设定项列表中使用

因此,Visual Studio 2019(16.9.5(抱怨在初始化器中使用this,尽管我只想要初始化的基部分(请参阅构造函数初始化列表中的执行顺序(。

有没有办法告诉编译器这一点(而不仅仅是禁用警告(?我发现的工作是:

#pragma warning (error: 4355)
struct A;
struct B;
struct AB {
A a;
B b;
};
struct MapCompare {
AB*the;
MapCompare(AB*ab):the(ab) {;}
bool operator()(int,int) const;
};
class Z {
AB ab;
A&a;
B&b;
std::map<int,int,MapCompare> m;
public:
Z():m{MapCompare{&ab}},a(ab.a),b(ab.b) {;}
...
};

注意:我尝试搜索类似的问题,发现Initialize a reference-warning C4355:';这';:在基成员初始值设定项列表中使用但不同的是,我想提取已初始化的基类部分,这使其安全(只要成员按此顺序排列(。

考虑一下同样出错的情况:

class z {
int a = 5;
int num;
public:
z() :num(this->a) {}
};

根据文档"编译器警告C4355",此指针不能在基类的初始值设定项列表中使用。默认情况下,此警告处于关闭状态。该代码段的作用类似于提供的示例:CDerived((:CBase(this(。此对象未完全构造,(对于编译器(使用不安全。你需要给它一个例子。