为什么我需要使用 :: 来表示一个函数是成员函数,但在实例变量方面我不需要这样做?我确实理解 :: 用于区分独立函数和成员函数,但我仍然不理解变量部分。我会举个例子来说明。
Shape.h
# pragma once
class Shape {
private:
int height;
int width;
public:
Shape(int height, int width);
int getHeight();
int getWidth();
}
Shape.cpp
#include "Shape.hpp"
Shape::Shape(int height, int width) {
this->height = height;
this->width = width;
}
int Shape::getHeight() {
return height;
}
int Shape::getWidth() {
return width;
}
在这里,我必须指定Shape
构造函数和getter的类,以便编译器知道我在说什么。那么当我执行return height;
或this->height
时,没有指定类,它是如何理解我所说的内容的。
::
来定义(静态)成员变量;这些只是比较少见的情况。 - Davis Herringthis->
只是"必需的",因为您将类成员命名为函数参数(并选择不使用构造函数初始化列表) - M.M