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

Using (::) in a class's member function definition

本文关键字:定义 成员 函数      更新时间:2023-10-16

我正在测试课程,我做了此类

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();
};

现在,我继续为所有公共功能编写了功能定义,但是,

当我写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);
}

我注意到之前的两个功能定义具有完全相同的效果。

我认为没有::操作员,它将无法使用,因为它会搜索班级外部的功能,因为我不再表示他们在点类中

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

谢谢。

::是范围分辨率运算符;它可以告诉编译器在哪里寻找名称。

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

set_x(new_x);

的缩写
this->set_x(new_x);

Point::set_x(new_x);

等效于

this->Point::set_x(new_x);

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

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

您可以使用此语法可以做的一件事是从基类的覆盖虚拟函数中调用父类的成员函数,从而使您可以使用基类提供的"默认实现"。您也可以从班级外部进行,类似于隐藏的功能:

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

在类成员函数中,所有类成员名称均处于范围,因此找到set_x

此外,类名称本身在类成员函数中可见(据说是注射),因此也找到了Point::set_x。但是出于同样的原因,Point::Point::set_xPoint::Point::Point::Point::set_x也是命名函数的方法。

::是范围分辨率运算符。要访问Point类名称空间范围的函数,您可以使用::操作员,但是由于函数setit(int new_x, int new_y)已经与set_xset_y相同的范围,因此无需定义这些功能的整体范围。该程序将在最本地范围中使用匹配符号与set_xset_y调用功能。