3

我对术语名称隐藏和信息隐藏感到非常困惑。最重要的是,c++ 中的隐藏规则是什么?谁能给我一个定义?

4

3 回答 3

6

Name hiding happens when you override a class:

struct A
{
    int x;
    int y;

    void foo();
    void bar();
};

struct B : A
{
    int y;
    void bar();
};

In class B, the names x and foo are unambiguous and refer to the names in the base class. However, the names y and bar hide the base names. Consider the following:

B b;
b.bar();

The function name refers to the name of the function B::bar without ambiguity, since the base name is hidden. You have to say it explicitly if you want the base function: b.A::bar(). Alternatively, you can add using A::bar; to your class definition to unhide the name, but then you have to deal with the ambiguity (this makes sense if there are distinct overloads, though).

Perhaps one of the most frequently confusing examples of name hiding is that of the operator=, which exists in every class and hides any base class operator; consequently, an implicit definition of the operator is produced for each class which doesn't provide an explicit one, which may come as a surprise if you already defined an assignment operator in a base class.

于 2013-09-08T21:28:51.583 回答
3

信息隐藏与封装相同。这是一个很好的起点http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29

于 2013-09-08T21:30:38.233 回答
2

“隐藏规则”表示,如果您派生一个类并在父级中添加一个与成员同名的成员,则该成员将“隐藏”父版本:

struct Base {
    void foo();
};

struct Derived : Base {
    void foo(int);
};

在这里,如果您尝试foo()在派生实例方法中使用,您将得到一个错误,即使foo()Base.

这样做的给定原因是为了避免混淆,例如 base 可能有void foo(double)和 derived void foo(int)。理由是最好停止编译,而不是在生成的程序中出现意外行为。

您可以在派生类中“导入”基名称,但这必须使用using.

于 2013-09-08T21:34:10.160 回答