对我认为非常基本的问题表示歉意。
我无法在线找出运算符::和 .在 C++ 中
我有几年的 C# 和 Java 经验,熟悉使用 .成员访问的运算符。
谁能解释一下什么时候会用到这些,有什么区别?
感谢您的宝贵时间
最佳答案
区别在于第一个是作用域解析运算符,第二个是成员访问语法。
因此,::
(范围解析)可用于访问命名空间中的其他内容,例如嵌套类,或访问静态函数。 .
句点运算符将简单地访问您正在使用它的类实例的任何可见成员。
一些例子:
class A {
public:
class B { };
static void foo() {}
void bar() {}
};
//Create instance of nested class B.
A::B myB;
//Call normal function on instance of A.
A a;
a.bar();
//Call the static function on the class (rather than on an instance of the class).
A::foo();
请注意,静态函数或数据成员属于类本身,无论您是否创建了该类的任何实例。所以,如果我的类中有一个静态变量,并且创建了该类的一千个实例,那么该静态变量的实例仍然只有一个。将有 1000 个其他非静态成员的实例,每个类实例一个。
一个更有趣的选择,当您遇到它时:)您还会看到:
//Create a pointer to a dynamically allocated A.
A* a = new A();
//Invoke/call bar through the pointer.
a->bar();
//Free the memory!!!
delete a;
如果你还没有学过动态内存,可能会有点困惑,所以我不会详细介绍。只是想让您知道您可以使用 { ::
或 .
或 ->
} 访问成员 :)
关于c++ - 何时使用 "::"何时使用 ".",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11442293/