-5

我只是好奇C++中的::和有什么区别?->

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

java或者C#如果你想调用一个函数或一个保留函数,你只需使用“。” 比如说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 使用::

4

2 回答 2

11

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

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

.直接引用运算符,用于引用实例上的成员方法和字段。

由于 Java 没有真正的指针,因此间接引用运算符没有用处。

于 2013-05-27T12:18:29.753 回答
4

->当您有一个指向对象的指针并取消引用该指针时,将使用该运算符,即

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;
...
}

参见维基百科

于 2013-05-27T12:18:57.867 回答