C++ 何时使用 -> 或 ::

C++ When do I use -> or ::

本文关键字:gt 何时使 C++      更新时间:2023-10-16

我知道在C++中,您使用->::而不是C#等语言中的.来访问对象的值,例如 button->TextSystem::String^,但我不知道什么时候应该使用->::,这非常令人沮丧,因为它会导致我许多编译器错误。如果您能提供帮助,我将不胜感激。谢谢:)

->是当您访问指针变量的成员时。 EG:myclass *m = new myclass(); m->myfunc(); 在指向myclass的指针上调用myfunc()::是范围运算符。这是为了显示某物在什么范围内。 因此,如果myclass在命名空间foo中,那么您将编写foo::myclass mc;

  • ->,如果您有指向某个对象的指针,这只是取消引用该指针并访问其属性的快捷方式。

    pointerToObject->member(*pointerToObject).member相同

  • :: 用于从某个范围访问内容 - 它仅适用于命名空间和类/结构范围。

    namespace MyNamespace {
      typedef int MyInt;
    }
    MyNamespace::MyInt variable;
    

与您的问题所述相反,您确实在C++中使用了.。相当多。

.(与非指针一起使用以访问成员和方法)

std::string hello = "Hello";
if (hello.length() > 3) { ... }

->(与用于访问成员和方法的指针一起使用)

MyClass *myObject = new MyClass;
if (myObject->property)
    myObject->method();

::(范围解析)

void MyClass::method() { ... } //Define method outside of class body
MyClass::static_property; //access static properties / methods

:: 也用于命名空间解析(请参阅第一个示例 std::string ,其中 string 位于命名空间std 中)。

我试图展示一些::.->用法的例子。我希望它有帮助:

int g;
namespace test
{
  struct Test
  {
     int x;
     static void func();
  };
  void Test:: func() {
     int g = ::g;
  }
}
int main() {
  test::Test v;
  test::Test *p = &v;
  v.x = 1;
  v.func();
  p->x = 2;
  p->func();
  test::Test::func();
}

左操作数是指针时应用 Opertor ->。例如考虑

struct A
{
   int a, b;
   A( int a, int b ) : a( a ), b( this->a * b ) {}
};

运算符 :: 引用正确操作数所属的类或空间。例如

int a;
strunt A
{
   int a;
   A( int a ) { A::a = a + ::a; }
};

使用句点,然后左操作数是对象的左值。例如

struct A
{
   int x;
   int y;
};
A *a = new A;
a->x = 10;
( *a ).y = 20;