gpt4 book ai didi

c++ - 用户定义的转换运算符到不可访问的基类

转载 作者:行者123 更新时间:2023-11-30 03:30:33 25 4
gpt4 key购买 nike

当基类不可访问时,为什么不允许用户定义的转换为基类(或引用它):protectedprivate

当有一个类 D 和它的 public 基类 B 时,有一个隐式规则将引用绑定(bind)到 B(B&B&&,可能是 cv 限定的)到类 D 的对象,因此用户定义的转换为 B& 没有意义。但是当基类是protectedprivate 时,隐式规则不再适用。那么为什么不允许使用用户定义的转换为 B&(或 const B&B&& 等)?

最佳答案

这是允许的,标准中没有任何内容禁止这样做。但它只是声明永远不会使用这样的转换运算符。 [class.conv.fct]/1 :

A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it), or to (possibly cv-qualified) void.

重载决议总是优先选择基类构造函数而不是转换运算符,转换运算符永远不会被调用,因此对于隐式转换来说是不必要的。访问检查总是在重载解析之后完成,因此从不考虑转换运算符。

struct B {
B() = default;
B(const B&) = default;
B& operator=(const B&) = default;
};

struct D : protected B {
operator B() { return *this; }
};

int main() {
D d;
B b = d; // (1)
b = d; // (2)
}

对于 (1),复制构造函数 B(const B&) 比使用转换运算符将 D 转换为 B 更好( [over.match.ctor]/1 ),以便选择构造函数。但是现在才检查访问,因为 B 的复制构造函数是 protected,所以它不会编译。

对于 (2) 几乎完全相同的事情。 B& operator=(const B&) 由重载决策选择,因为它比调用 D 的用户定义转换运算符更匹配。但是现在 B 的赋值运算符也被 protected,所以你不能在 D 之外访问它,你的代码也不会编译。

据我所知,这就是重载解析的工作原理。

关于c++ - 用户定义的转换运算符到不可访问的基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44864106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com