在C++中使用::

foo*_*512 38 c++ namespaces function

我正在学习C++,我无法告诉我何时需要使用它::.我知道我需要使用std::前面coutcin.这是否意味着的是内部iostream文件创建它做了一个叫做命名空间的开发std,并把功能cincout进入所谓的命名空间std?当我创建一个不属于同一文件的新类时,main()我必须添加::.

例如,如果我创建一个class被调用的A,为什么我需要放在我创建的A::函数前面,即使我没有把它放到名字中?例如void A::printStuff(){}.如果我在中创建一个函数main,为什么我不必放main::printStuf{}

我知道我的问题可能令人困惑,但有人可以帮助我吗?

Jos*_*eld 56

您即将相当多的权利coutcin.它们是std命名空间内定义的对象(不是函数).以下是C++标准定义的声明:

标题<iostream>简介

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}
Run Code Online (Sandbox Code Playgroud)

::被称为范围解析运算符.名称coutcin定义在内std,所以我们必须用他们的名字限定std::.

类的行为有点像名称空间,因为类中声明的名称属于类.例如:

class foo
{
  public:
    foo();
    void bar();
};
Run Code Online (Sandbox Code Playgroud)

命名的构造函数foo是名为的类的成员foo.它们具有相同的名称,因为它是构造函数.该功能bar也是其中的一员foo.

因为他们是成员foo,当从课堂外提到他们时,我们必须限定他们的名字.毕竟,他们属于那个阶级.因此,如果您要定义构造函数并bar在类外部,则需要这样做:

foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}
Run Code Online (Sandbox Code Playgroud)

这是因为他们被定义之外的类.如果您没有foo::对名称进行限定,那么您将在全局范围内定义一些新函数,而不是作为成员foo.例如,这完全不同bar:

void bar()
{
  // Implement different bar
}
Run Code Online (Sandbox Code Playgroud)

允许它与foo类中的函数具有相同的名称,因为它在不同的范围内.这bar是在全球范围内,而另一个bar属于foo该类.


sco*_*nes 19

::用于取消引用范围.

const int x = 5;

namespace foo {
  const int x = 0;
}

int bar() {
  int x = 1;
  return x;
}

struct Meh {
  static const int x = 2;
}

int main() {
  std::cout << x; // => 5
  {
    int x = 4;
    std::cout << x; // => 4
    std::cout << ::x; // => 5, this one looks for x outside the current scope
  }
  std::cout << Meh::x; // => 2, use the definition of x inside the scope of Meh
  std::cout << foo::x; // => 0, use the definition of x inside foo
  std::cout << bar(); // => 1, use the definition of x inside bar (returned by bar)
}
Run Code Online (Sandbox Code Playgroud)

不相关:cout和cin不是函数,而是流对象的实例.

编辑 修正为Keine Lust建议

  • 不应该在`meh`中使用`static const int x = 2;`吗? (2认同)

Joh*_*nic 18

::被称为作用域解析运算符.可以像这样使用:

:: 标识符
类名 :: 标识符
命名空间 :: 标识符

你可以在这里阅读它
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017

  • 链接它们都没错:`myNamespace :: myClass :: myMember`或`:: std :: cout`。 (2认同)

小智 8

“一元范围解析运算符”或“冒号冒号运算符”的一种用途是用于相同名称的局部和全局变量选择:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }
Run Code Online (Sandbox Code Playgroud)

结果输出将是:

这是主要功能的本地:30

这是主要功能的全局:20

其他用途可能是:从类外部定义函数、访问类内的静态变量或使用多重继承。