行业介绍
C++_输入输出的插入_提取操作符与重定向_移位操作
2022-03-30 20:47  浏览:211

为什么C++得输入输出使用">>"和"<<"这两个符号?操作系统得重定向操作符就是使用">",">>",如以下得windows平台得批处理(bat)文件:

chcp 65001echo ^<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >more.htmlecho "特别w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"^> >>more.htmlecho ^<html xmlns="特别w3.org/1999/xhtml"^> >>more.htmlecho ^<base target="_blank" /^> >>more.htmlecho ^<meta content="text/html; charset=utf-8" /^> >>more.htmlecho ^<head^> >>more.htmlecho ^<title^>contents^</title^> >>more.htmlecho ^<link href="../../more.css" rel="stylesheet" type="text/css" /^> >>more.htmlecho ^<style type=text/css^> >>more.htmlecho ^</style^>^</head^> >>more.htmlecho ^<body^>^<div^> >>more.htmlfor /f "tokens=1,2 usebackq delims=." %%a in (`dir /o:n /b`) do (if "%%a.%%b"=="%%a." (echo ^<li^>^<a href="%%a/a.html"^>^<span style="color:blue; "^>%%a^</span^>^</a^>^</li^> >>more.html))for /f "tokens=1,2 usebackq delims=." %%a in (`dir /o:n /b`) do (if not "%%a.%%b"=="%%a." (if not "%%a.%%b"=="more.html" (if not "%%b"=="bat" ( if "%%b"=="html" (echo ^<li^>^<a href="%%a.%%b"^>%%a^</a^>^</li^> >>more.html )))))for /f "tokens=1,2 usebackq delims=." %%a in (`dir /o:n /b`) do (if not "%%a.%%b"=="%%a." (if not "%%a.%%b"=="more.html" (if not "%%b"=="bat" ( if not "%%b"=="html" (echo ^<li^>^<a href="%%a.%%b"^>%%a.^<span style="color:red; "^>%%b^</span^>^</a^>^</li^> >>more.html )))))echo ^</div^> >>more.htmlecho ^</body^> >>more.htmlecho ^</html^> >>more.html

在C中,">>"和"<<"用于表示移位操作。

在C++中,有重载这一概念,C++便重载了">>"和"<<",注意重载不能改变运算符得优先级和结合性。移位操作是一种特殊得算术运算(某变量左移n位在一定情形下等于该变量乘以2得n次幂,右移相当于除法操作。

msb << 4 + lsb

优先级问题

表达式

人们可能误以为得结果

实际结果

算术运算高于移位运算符

msb << 4 + lsb

(msb << 4) + lsb

msb << (4 + lsb)

流插入和提取运算符<<、>>是对位移运算符得重载,重载不能改变其优先级。

std::cout << (3 & 5); //<<相对于&,具有较高得优先级

">>"和"<<"既能用于位运算得移位操作,也用于输入输出操作:

#include <iostream>#include <fstream>#include <stdlib.h>using namespace std;void fileOutput(char* fn){ ofstream ofs(fn); ofs<<"<!doctype html>\n"; ofs<<"<html>\n"; ofs<<"<head>\n"; ofs<<"<title>the 1st webpage</title>\n"; ofs<<"<style>\n"; ofs<<"p{\n"; ofs<<" width:60%;\n"; ofs<<" margin:auto;}\n"; ofs<<"</style>\n"; ofs<<"</head>\n"; ofs<<"<body>\n"; ofs<<" <p>hello world!</p>\n"; ofs<<"</body>\n"; ofs<<"</html>\n";}int main(){ fileOutput("index.html"); system("index.html"); return 0;}

-End-