簡體   English   中英

點和作用域分辨率運算符類對象之間的區別

[英]Difference between dot and Scope Resolution Operator Class Object

#include<iostream>

using namespace std;

class der
{
public:
    void fun()
    {
        cout << "Good";
    }
};

int main()
{
    der a;
    a.der::fun(); // method 1
    a.fun(); // method 2

    return 0;
}

我知道, ::用於訪問名稱空間或嵌套類的內容...但是我在代碼中提到的方法1和方法2之間的主要區別是什么? 兩者都工作正常...

謝謝。

a.der::fun(); 僅使用顯式類作用域。 這對您的情況沒有任何影響。

如果您想顯式調用der公開繼承的基類函數,這將變得很有意思。

您可以使用它來調用基類中的方法,有時甚至需要消除該調用的歧義。 例:

#include <iostream>

struct B
{
    void foo() { std::cout << "B::foo" << std::endl; }
};

struct B2
{
    void foo() { std::cout << "B2::foo" << std::endl; }
};

struct A : public B
{
    void foo() { std::cout << "A::foo" << std::endl; }
};

struct C : public B, public B2
{
};

int main()
{
    A a;
    a.foo(); // calls A::foo
    a.B::foo(); // calls B::foo

    C c;
    c.B2::foo(); // calls B2::foo, needed to disambiguate from B::foo

    return 0;
}

現場例子

讓我們舉個例子:

class A {
    public:
        virtual void foo() { /* ... */ }
};

class B : public A {
    public:
        void foo() { /* ... */ }
};

int main() {
    B b;
    b.foo(); // this performs B::foo() on b object
    b.A::foo(); // this performs A::foo() on b object
}

這樣便可以訪問您重載的方法。 它甚至不必是虛擬方法,只需具有相同的名稱和參數即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM