需要 :: 为函数指定 class 而不是变量?
Need of :: to specify class for functions but not variables?
为什么我需要使用 :: 来表示函数是否是成员函数,而我不需要为实例变量这样做?我确实知道 :: 用于区分独立函数和成员函数,但我仍然不了解变量部分。我会举个例子来说明我在说什么。
Shape.h
# pragma once
class Shape {
private:
int height;
int width;
public:
Shape(int height, int width);
}
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
构造函数的 class 和 getter,以便编译器知道我在说什么。那么,当我执行 return height;
或 this->height
而不指定 class 时,它为什么会理解我在说什么。
C++ 使用一个模型,在该模型中,除非另有说明,否则它最初假定所有内容都与声明的内容相同 namespace/class。所以,例如,如果你写
int getHeight() {
return height;
}
在 C++ 文件的顶层,编译器假定您在全局命名空间中声明某些内容。这意味着 getHeight
是一个自由函数。然后,语句 return height;
在全局命名空间中的自由函数的上下文中进行解释 - 它将开始搜索局部变量 height
,然后是全局命名空间中的全局变量。
另一方面,如果你写
int Shape::getHeight() {
return height;
}
你明确地告诉 C++ "hey, I know that this code is in the global namespace at the top level, but I'm explicitly indicating that this is actually inside of the Shape
class." 在这一点上,编译器说 "ah, gotcha, you're inside Shape
now" 并解释编写的代码,就好像它在 Shape
中一样。从这个意义上讲,语句 return height;
首先开始寻找一个名为 height
的局部变量,然后寻找一个名为 Shape
的数据成员 height
,然后寻找名为 height
的全局变量height
.
C++ 必须以这种方式做事并没有根本原因,但它有一个很好的内部一致性。你停留在任何 "scope level" 出现的语句或定义,除非有明确的东西让你进入不同的范围级别。因此,一旦您以某种方式声明了函数,表明它位于 Shape
中,其中的所有内容都会相对于 Shape
而不是全局命名空间进行计算。
希望对您有所帮助!
但不是变量。这不是真的,如果你想获得 A
class.
范围之外的值,你必须使用 ::
class A {
public:
const static int a = 5;
A (){}
};
int main (void) {
std::cout << A::a;
}
为什么我需要使用 :: 来表示函数是否是成员函数,而我不需要为实例变量这样做?我确实知道 :: 用于区分独立函数和成员函数,但我仍然不了解变量部分。我会举个例子来说明我在说什么。
Shape.h
# pragma once
class Shape {
private:
int height;
int width;
public:
Shape(int height, int width);
}
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
构造函数的 class 和 getter,以便编译器知道我在说什么。那么,当我执行 return height;
或 this->height
而不指定 class 时,它为什么会理解我在说什么。
C++ 使用一个模型,在该模型中,除非另有说明,否则它最初假定所有内容都与声明的内容相同 namespace/class。所以,例如,如果你写
int getHeight() {
return height;
}
在 C++ 文件的顶层,编译器假定您在全局命名空间中声明某些内容。这意味着 getHeight
是一个自由函数。然后,语句 return height;
在全局命名空间中的自由函数的上下文中进行解释 - 它将开始搜索局部变量 height
,然后是全局命名空间中的全局变量。
另一方面,如果你写
int Shape::getHeight() {
return height;
}
你明确地告诉 C++ "hey, I know that this code is in the global namespace at the top level, but I'm explicitly indicating that this is actually inside of the Shape
class." 在这一点上,编译器说 "ah, gotcha, you're inside Shape
now" 并解释编写的代码,就好像它在 Shape
中一样。从这个意义上讲,语句 return height;
首先开始寻找一个名为 height
的局部变量,然后寻找一个名为 Shape
的数据成员 height
,然后寻找名为 height
的全局变量height
.
C++ 必须以这种方式做事并没有根本原因,但它有一个很好的内部一致性。你停留在任何 "scope level" 出现的语句或定义,除非有明确的东西让你进入不同的范围级别。因此,一旦您以某种方式声明了函数,表明它位于 Shape
中,其中的所有内容都会相对于 Shape
而不是全局命名空间进行计算。
希望对您有所帮助!
但不是变量。这不是真的,如果你想获得 A
class.
::
class A {
public:
const static int a = 5;
A (){}
};
int main (void) {
std::cout << A::a;
}