c++ - 为什么不推荐使用访问声明?这对于 SRO 和 using 声明意味着什么?

标签 c++ deprecated language-lawyer

我一直在寻找一个我认为相当简单的问题的答案:为什么访问声明被弃用?

class A
{
public:
    int testInt;
}

class B: public A
{
private:
   A::testInt;
}

据我了解,只需在 A::testInt 前面加上“using”即可修复此问题, 但如果不了解为什么我必须这样做,这感觉就像是一个廉价的解决方案。

更糟糕的是,它混淆了我对使用声明/指令和范围解析运算符的理解。如果我必须在此处使用 using 声明,为什么我可以在其他地方使用 SRO 而只能使用 SRO?一个简单的例子是 std::cout。为什么不使用std::cout?我曾经认为 using 和 SRO 或多或少是可以互换的(提供或获取“using”关键字提供的一些方便的功能,我知道这一点,至少在命名空间的情况下)。

我在标准中看到了以下内容:

The access of a member of a base class can be changed in the derived class by mentioning >its qualified-id in the derived class declaration. Such mention is called an access >declaration. The effect of an access declaration qualified-id; is defined to be equivalent >to the declaration using qualified-id; [Footnote: Access declarations are deprecated; member >using-declarations (7.3.3) provide a better means of doing the same things. In earlier >versions of the C++ language, access declarations were more limited; they were generalized >and made equivalent to using-declarations - end footnote]

然而,这除了证实我已经知道的事情之外没有任何作用。如果您真的将其归结为一个事实,我确信我的问题源于这样一个事实:我认为 using 和 SRO 是可以互换的,但我没有看到任何其他建议。

提前致谢!

最佳答案

If I must use a using declaration here, why am I able to use the SRO and only the SRO elsewhere?

嗯?你做不到。不要在不同的范围内重新声明名称(这是访问声明的作用)。

A trivial example is std::cout. Why not use using std::cout?

因为它们不是同一件事,甚至不相近。

一个引用名称,另一个重新声明名称。

I am sure my problem stems from the fact that I think using and the SRO are interchangeable

我同意这是你的问题,因为你完全错了。在 using 声明之后,不需要限定名称,但这并不会使它们可以互换。

std::cout 是一个表达式,它引用变量,因此您可以对其进行写入、将其作为函数参数传递、获取其地址等。

using std::cout; 是一个声明。它使名称 cout 在当前作用域中可用,作为名称 std::cout 的别名。

std::cout << "This is an expression involving std::cout\n";
using std::cout;  // re-declaration of `cout` in current scope

如果您建议为了保持一致性,您应该这样做以写入cout:

using std::cout << "This is madness.\n";

那么,呃,这太疯狂了。

在类中,当您想要重新声明具有不同访问权限的成员时,您就是在重新声明它,因此您需要一个声明。您并不是试图引用要写入的对象以将其包含在某些表达式中,该表达式(如果在类范围内允许)将如下所示:

class B: public A
{
private:
   A::testInt + 1;
};

为了与语言的其余部分保持一致,从基类重新声明名称是使用 using-declaration 完成的,因为这是一个声明,它不是使用看起来像表达。

class B: public A
{
private:
   A::testInt; // looks like an expression involving A::testInt, but isn't
   using A::testInt;  // re-declaration of `testInt` in current scope
};

将此与上面的 std::cout 示例进行比较,您会发现要求 using 是完全一致的,并且从 C++ 中删除访问声明使语言更加一致.

关于c++ - 为什么不推荐使用访问声明?这对于 SRO 和 using 声明意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22441288/

相关文章:

c++ - Qt 与 QAMQP/RabbitMQ

c++ - 将具有 const 字段的对象插入到容器中

C#: "Obsolete"函数和 "Deprecated"函数有什么区别?

c - 通过 const 左值访问非常量对象是否安全?

C-两个指针之间的转换行为

c++ - 在 C++ 中将字符串解析为数字数组?

c++ - 如何更改 QGraphicsItem 对象的颜色?

Java:为什么不推荐使用 Date 构造函数,而我改用什么?

ruby-on-rails - 使用 ActiveSupport::Deprecation 标记已弃用的方法

arrays - 为什么不保留空数组和哈希值?