gpt4 book ai didi

c++ - 在 C++ 中使用::(范围解析运算符)

转载 作者:IT老高 更新时间:2023-10-28 12:34:07 28 4
gpt4 key购买 nike

我正在学习 C++,但我不知道何时需要使用 :: 。我知道我需要在 coutcin 前面使用 std::。这是否意味着在 iostream 文件中,创建它的开发人员创建了一个名为 std 的命名空间并将函数 cincout 进入名为 std 的命名空间?当我创建一个与 main() 不在同一个文件中的新类时,我必须添加 :: .

例如,如果我创建一个名为 Aclass ,为什么我需要将 A:: 放在一个函数前面我做了,即使我没有把它放到命名空间中?例如 void A::printStuff(){} 。如果我在 main 中创建一个函数,为什么不用 main::printStuff{}

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

最佳答案

关于 cout 你说得很对和 cin .它们是定义在 std 中的对象(不是函数)。命名空间。以下是 C++ 标准定义的声明:

Header <iostream> synopsis

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

::被称为作用域解析运算符。姓名coutcinstd 中定义, 所以我们必须用 std:: 来限定他们的名字.

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

class foo
{
public:
foo();
void bar();
};

名为 foo 的构造函数是名为 foo 的类的成员 .它们具有相同的名称,因为它的构造函数。函数bar也是 foo 的成员.

因为他们是 foo 的成员,当从类外引用他们时,我们必须限定他们的名字。毕竟,他们属于那个类(Class)。所以如果你要定义构造函数和bar在类之外,你需要这样做:

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

void foo::bar()
{
// Implement bar
}

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

void bar()
{
// Implement different bar
}

允许与 foo 中的函数同名类,因为它在不同的范围内。这个bar在全局范围内,而另一个 bar属于 foo类。

关于c++ - 在 C++ 中使用::(范围解析运算符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15649580/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com