在类的成员函数定义中使用 (::)
Using (::) in a class's member function definition
我正在测试课程,我做了此类
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_x
和Point::Point::Point::Point::set_x
也是命名函数的方法。
::
是范围分辨率运算符。要访问Point
类名称空间范围的函数,您可以使用::
操作员,但是由于函数setit(int new_x, int new_y)
已经与set_x
和set_y
相同的范围,因此无需定义这些功能的整体范围。该程序将在最本地范围中使用匹配符号与set_x
和set_y
调用功能。
相关文章:
- 为什么我不能在一个类的不同行中声明和定义成员变量?
- C++令牌定义成员
- 在没有类定义的标头中定义成员变量
- 如何在类的构造函数中定义成员向量的大小
- 如何在C++中动态定义成员函数
- C++ Boost.Serialization - 用户定义成员的非侵入式序列化
- C++类 - 使用公共变量并在类外定义成员函数
- G++ - 对已定义成员函数的未定义引用
- 在哪里以及如何定义成员变量?在头文件还是实现文件中?
- 是否可以修改STL并自定义成员函数
- 从 boost::mpl:vector 类型列表中定义成员变量
- 在构造对象时定义成员函数
- 为什么定义成员函数指针变量需要类名
- 复制构造函数中的 C++ 用户定义成员
- 如何根据类参数定义成员类运算符
- 使用指向未定义成员函数的指针时的未定义引用
- 如何在运行时定义成员数组大小
- C++-在模板类之外但在头中定义成员函数
- c++在不知道对象类型的情况下定义成员函数指针
- 在特定偏移量中定义成员的结构