在尝试熟悉 C++ 及其概念时,我遇到了
using namespace std
和
#include <iostream>
我的简单代码如下
#include "stdafx.h"
#include "ConsoleApplication5.h"
#include <iostream>
int main()
{
std::cout << "hi";
return 0;
}
使用使用 intellisense 的 Visual Studio 2015 Community 显示
cout
使用以下内容
std::ostream std::cout
作为一名 C# 程序员,这让我有些困惑。这是:
std::ostream
作为返回类型而
std::cout
是传递的方法/参数还是
std::ostream
依赖于
cout
更新(在 Archimaredes 回答之后)
在 C# 中,可以使用以下内容:
StreamWriter srWrite;
或
StreamWriter srWrite = new StreamWriter(string filepath)
或者可以使用:
StreamWriter srWrite = new StreamWriter(new NetworkStream(Socket.GetStream()));
每例一个对象类型即
StreamWriter
可分配给新对象或现有文件或网络流。
在你提到的(请原谅 C# 心态)之后,我用 std::ostream x = new std:ostream
尝试了相同的方法,它返回一个无默认构造函数。
您能否添加 std::ostream 和 std::cout 如何相互关联,从而创建/初始化另一个。这个概念对我来说还是有点模糊。
最佳答案
std::cout
是全局范围内的对象,类型为 std::ostream
.当您调用 std::cout << "hi"
, 你正在调用 operator<<()
方法与 std::cout
对象作为您的左手值和字符串文字 "hi"
作为右边的值。
cout
和 ostream
在std
里面命名空间,因此是 std::
字首。如果你放置 using namespace std
在您的代码中,这允许您省略前缀,例如
#include <iostream>
using namespace std;
int main() {
cout << "hi"; // no error because the 'std' is unnecessary now
}
命名空间用于防止名称冲突,与 C# 完全相同; 不使用 using namespace
通常是个好习惯整个源代码文件的指令,以防止代码中的名称冲突。
根据 OP 的更新进行编辑
std::cout
是 std::ostream
的实例 .为了说明这一点,请考虑以下内容:
class A_Class {
public:
A_Class() {}
void foo() {}
};
int main() {
A_Class an_instance;
an_instance.foo();
}
A_Class
是一个类,而 an_instance
是 A_Class
的实例.
同样; ostream
是一个类,而 cout
是 ostream
的实例.
根据 OP 的评论进行编辑
这可能会让 C# 用户感到困惑,但它与以下概念完全相同:
int n = 5;
在哪里int
是类型,n
是变量名。
关于c# - c++ - 使用 std 命名空间和依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35037637/