在类的成员函数定义中使用(::)

Moh*_*bil 1 c++ oop class function

我正在测试课程,我上了这门课

class Point
{
private:
    int x,y;
public:
    void setit(int new_x,int new_y);
    void set_x(int new_x);
    void set_y(int new_y);
    int get_x();
    int get_y();
};
Run Code Online (Sandbox Code Playgroud)

现在我继续编写所有公共函数的函数定义,但是,

在编写void set(int new_x,int new_y); 函数定义时,有些东西让我感到困惑

void Point::setit(int new_x, int new_y){
    Point::set_x(new_x);
    Point::set_y(new_y);
}

void Point::setit(int new_x, int new_y){
    set_x(new_x);
    set_y(new_y);
}
Run Code Online (Sandbox Code Playgroud)

我注意到前两个函数定义具有完全相同的效果.

我认为如果没有::运算符它将无法工作,因为它会搜索类外的函数,因为我不再表示它们在Point类中

任何人都可以解释为什么他们都有相同的效果?

谢谢.

Set*_*gie 6

::是范围解析运算符; 它可以告诉编译器到哪里查找名称.

Point::set_x只是调用成员函数的扩展语法.

set_x(new_x);
Run Code Online (Sandbox Code Playgroud)

是简称

this->set_x(new_x);
Run Code Online (Sandbox Code Playgroud)

Point::set_x(new_x);
Run Code Online (Sandbox Code Playgroud)

相当于

this->Point::set_x(new_x);
Run Code Online (Sandbox Code Playgroud)

它允许您在类隐藏父类中的函数时选择要调用的函数.例如:

struct A {
    void f();
};

struct B : public A {
    void f(); // Hides A::f
};

B binst;

binst.f(); // Calls B::f

binst.A::f(); // Calls A::f
Run Code Online (Sandbox Code Playgroud)

使用此语法可以做的一件事是从基类的重写虚函数调用父类的成员函数,允许您使用基类提供的"默认实现".您也可以在课外进行,类似于隐藏功能:

struct A {
    virtual void f() {
        cout << "A::f" << endl;
    }
};

struct B : public A {
    virtual void f() override {
        cout << "B::f" << endl;

        A::f(); // if we just did f(), it would call B::f, and we
                // would get infinite recursion
    }
};

B b;

b.f();    // prints B::f A::f
b.A::f(); // prints B::f
Run Code Online (Sandbox Code Playgroud)

  • @MohamedAhmedNabil没有简单的答案,不会牺牲完整性或真实性. (3认同)