C++"::"和"->"的差异

C++ difference of "::" and "->"

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

我只是好奇::->在c++中的区别是什么?

目前正在学习c++,因为我想学习openGL和很多使用c++的openGL教程,所以我会选择有很多教程的语言:)

javaC#中,如果您想调用函数或保留函数,只需使用"。",例如text1.getText();如果要转换为C++,会是text1->getText()吗?怎么称呼它们呢?标题不合适。如果->等于java中的".",那么"::"的用途是什么?我相信还有很多像我这样的问题,但我不知道该怎么称呼它们,所以我无法获得准确的信息。顺便说一下,我发现这个::认为,而使用sfml。

下面是一个例子

if (event.type == sf::Event::Closed)
            {
                // end the program
                running = false;
            }
            else if (event.type == sf::Event::Resized)
            {
                // adjust the viewport when the window is resized
                glViewport(0, 0, event.size.width, event.size.height);
            }
void renderingThread(sf::Window* window)
    {
        // activate the window's context
        window->setActive(true);

        // the rendering loop
        while (window->isOpen())
        {
            // draw...
            // end the current frame -- this is a rendering function 
(it requires the context to be active)
                window->display();
            }
        }

window使用->,而sf使用::

::作用域解析操作符,用于引用静态类成员和命名空间元素。

->间接引用操作符,用于引用实例指针上的成员方法和字段。

.直接引用操作符,用于引用实例中的成员方法和字段。

由于Java没有真正的指针,所以没有必要使用间接的引用操作符

操作符->用于当你有一个指向对象的指针并且指针解引用时,即

string* str = new string("Hello, World");
const char* cstr = str->c_str();

string str("Hello World");
const char* cstr = str.c_str();

用于直接引用成员。

::是"作用域操作符"。您可以使用它来调用类的static成员或引用namespace中的成员。

namespace X{
 int a;
}
int main() {
...
X::a = 4;
...
}

参见维基百科