C++程序结构
发表于:2024-12-07 | 分类: C++
字数统计: 665 | 阅读时长: 3分钟 | 阅读量:

C++程序结构,结构,命名空间,输入输出

程序结构

基本案例

  • 头文件.h
  • 源文件.cpp
1
2
3
4
5
6
#ifndef MY_H
#define MY_H

void printMessage();

#endif
1
2
3
4
5
6
7
#include <iostream>
using namespace std;
#include "myheader.h"
void printMessage()
{
cout << "Hello, World!" << endl;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "myheader.h"

using namespace std;

int main()
{
cout << "Program starts!" << endl;

printMessage();

return 0;
}

iostream头文件

C++程序中处理标准输入输出的基础工具

  • 输入输出流对象std::cin(输入),std::cout(输出),std::cerr(错误输出),std::clog(日志输出)。
  • 操作符<<(输出运算符),>>(输入运算符)。

命名空间

  • 前面的std是标准命名空间
  • 命名空间将标识符(如变量)划分到一个命名空间下。即使不同命名空间中定义了相同的标识符,程序仍然能区分它们。

定义和使用命名空间

定义

1
2
3
namespace name{
//变量、方法、类等
}

使用

域解析操作符

显示使用,对于大型项目推荐

1
命名空间::命名空间成员
using namespace
  • 引入整个命名空间
  • 可以直接使用命名空间中的所有标识符,无需使用::,支持多个命名空间

不推荐在头文件中使用 using namespace (会全部引入)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef MY_NAMESPACE_H
#define MY_NAMESPACE_H

namespace MyNamespace {
// 一个简单的函数
void sayHello() {
std::cout << "Hello from MyNamespace!" << std::endl;
}

// 另一个函数
int add(int a, int b) {
return a + b;
}
}

#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include "myheader.h"

using namespace std;
using namespace MyNamespace;
int main()
{
// 通过命名空间调用函数
sayHello();

// 调用命名空间中的另一个函数
int result = MyNamespace::add(5, 3);
cout << "5 + 3 = " << result << endl;

return 0;
}
using 声明
  • 只引入命名空间中的某个特定标识符,定义了的无需使用::

  • 如下方sayHellousing MyNamespace::sayHello;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "myheader.h"

using namespace std;

// 按需定义
using MyNamespace::sayHello;

int main()
{
// 通过命名空间调用函数
sayHello();

// 调用命名空间中的另一个函数
int result = MyNamespace::add(5, 3);
cout << "5 + 3 = " << result << endl;

return 0;
}

输入输出

  • cin>>value,也支持多个输入,添加>>即可
  • cout<<value<<endl,也支持多个输出,中间添加<<即可,endl表示换行,会刷新缓冲区(\n不会)
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
{
int a, b;
cout << "输入两个数字\n";
cin >> a >> b;
cout << "a=" << a << ",b=" << b << endl;
return 0;
}
上一篇:
C++运算符补充
下一篇:
Bamboo 组件