gpt4 book ai didi

c++ - operator const Base&() 是否应该用于不可访问的基类?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:07:09 26 4
gpt4 key购买 nike

我希望有一个类允许访问其基本情况的 const 接口(interface),但不允许访问其他类。特别是:

class B
{};

class A : private class B
{
public:
operator const B&() { return *this; }
};

int main()
{
A a;
const B& b = a; // Should this line be an error?
}

g++ 给出了一个不可访问的基类错误。你们那里的语言专家认为这个错误在 C++11/C++14 中是正确的吗?

是的,我意识到我可以(并且将会)这样做:

int main()
{
A a;
const B& b = a.operator const B&();
}

对这个构造的另一种方法有什么建议吗?

最佳答案

[dcl.init.ref]/5:

A reference to type “cv1 T1” is initialized by an expression of type “cv2 T2” as follows:

  • If the reference is an lvalue reference and the initializer expression

    • is an lvalue (but is not a bit-field), and “cv1 T1” is reference-compatible with “cv2 T2,” or
    • has a class type (i.e., T2 is a class type), where T1 is not reference-related to T2, [..]

    then the reference is bound to the initializer expression lvalue in the first case and to the lvalue result of the conversion in the second case (or, in either case, to the appropriate base class subobject of the object).

转换函数将在第二个要点中介绍。但是,BA 引用相关(并且兼容),即使它是私有(private)基类,所以第一个要点适用。现在 [dcl.init.ref]/4 将此场景定义为格式错误:

Given types “cv1 T1” and “cv1 T2”, “cv1 T1” is reference-related to “cv1 T2” if T1 is the same type as T2, or T1 is a base class of T2. “cv1 T1” is reference-compatible with “cv2 T2” if T1 is reference-related to T2 and cv1 is the same cv-qualification as, or greater cv-qualification than, cv2. In all cases where the reference-related or reference-compatible relationship of two types is used to establish the validity of a reference binding, and T1 is a base class of T2, a program that necessitates such a binding is ill-formed if T1 is an inaccessible [..] base class of T2.

这样的引用绑定(bind)总是会失败,不管有没有可用的转换函数。引用绑定(bind)不能与私有(private)继承一起使用。

您的显式调用是此问题的解决方案,尽管不再需要转换运算符:只需定义一个返回 const 引用的 getter。例如

const B& b = a.getB();

关于c++ - operator const Base&() 是否应该用于不可访问的基类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371174/

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