从 C# 到 C++ .运算符与 :: 和 ->

From C# to C++ The . Operator vs :: and ->

本文关键字:gt C++ 运算符      更新时间:2023-10-16

我对C++相当陌生。

通过一些现有的C++代码,我看到了使用的 :: 、. 和 -> 运算符。问题是,它们之间有什么区别,什么时候使用其中一个?

我偶尔在 C# 中看到过 :: 运算符,但我总是使用 . 来访问成员,隐式声明范围。假设这两个是C++中的等价物,我仍然不确定为什么我们使用箭头 -> 运算符以及为什么它似乎可以与点互换使用。算子。

谢谢。

::是范围运算符。 它用于说明您所处的范围:

// in the A.h file
class A
{
public:
    A();
    void foo();
};
// in the A.cpp file
#include "A.h"
A::A() // the scope of this function is A - it is a member function of A
{
}
void A::foo() // same here
{
}
void bar() // as written, this function is in the global scope ::bar
{
}

.运算符用于访问"堆栈"分配变量的成员。

A a; // this is an automatic variable - often referred to as "on the stack"
a.foo();

->运算符用于访问指向的内容(堆或堆栈)的成员。

A* pA = new A;
a->foo();
A a;
A* pA2 = &a;
pa2->foo();

它相当于(*pA).foo(). C# 没有自动变量的概念,因此它不需要取消引用运算符(这是 *pApA-> 正在做的事情)。 由于 C# 几乎将所有内容都视为指针,因此假定取消引用。