python 为什么 C++ 语法如此复杂?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1355803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is the C++ syntax so complicated?
提问by Iceland_Hyman
I'm a novice at programming although I've been teaching myself Python for about a year and I studied C# some time ago.
我是编程的新手,虽然我已经自学了大约一年的 Python 并且我前段时间学习了 C#。
This month I started C++ programming courses at my university and I just have to ask; "why is the C++ code so complicated?"
这个月我在我的大学开始了 C++ 编程课程,我只需要问;“为什么 C++ 代码这么复杂?”
Writing "Hello world." in Python is as simple as "print 'Hello world.'" but in C++ it's:
写“你好世界”。在 Python 中就像“打印 'Hello world.'”一样简单,但在 C++ 中它是:
# include <iostream>
using namespace std;
int main ()
{
cout << "Hello world.";
return 0;
}
I know there is probably a good reason for all of this but, why...
我知道这一切可能是有充分理由的,但是,为什么...
- ... do you have to include the <iostream> everytime? Do you ever notneed it?
- ... same question for the standard library, when do you not need std::*?
- ... is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
- ... do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
- ... do you need to return 0 even when you are never going to use it?
- ...你每次都必须包含 <iostream> 吗?你永远不会需要它吗?
- ... 标准库的同样问题,什么时候不需要 std::*?
- ...“主要”部分是一个函数吗?你有没有调用过 main 函数?为什么是整数?为什么 C++ 需要有一个 main 函数而 Python 不需要?
- ...你需要“std::cout <<”吗?与 Python 相比,这不是不必要的冗长和复杂吗?
- ...即使您永远不会使用它,您是否也需要返回 0 ?
This is probably because I'm learning such basic C++ but every program I've made so far looks like this, so I have to retype the same code over and over again. Isn't that redundant? Couldn't the compiler just input this code itself, since it's always the same (i.e. afaik you always include <iostream>, std, int main, return 0)
这可能是因为我正在学习如此基本的 C++,但到目前为止我编写的每个程序看起来都像这样,所以我必须一遍又一遍地重新键入相同的代码。那不是多余的吗?编译器不能自己输入这个代码,因为它总是相同的(即你总是包含 <iostream>, std, int main, return 0)
回答by coppro
C++ is a more low-level language that executes without the context of an interpreter. As such, it has many different design choices than does Python, because C++ has no environment which it can rely on to manage information like types and memory. C++ can be used to write an operating system kernel where there is no code running on the machine except for the program itself, which means that the language (some library facilities are not available for so-called freestanding implementations) must be self-contained. This is why C++ has no equivalent to Python's eval
, nor a means of determining members, etc. of a class, nor other features that require an execution environment (or a massive overhead in the program itself instead of such an environment)
C++ 是一种更底层的语言,它在没有解释器上下文的情况下执行。因此,它与 Python 相比有许多不同的设计选择,因为 C++ 没有可以依赖的环境来管理类型和内存等信息。C++ 可用于编写操作系统内核,其中除了程序本身外,机器上没有其他代码在运行,这意味着该语言(某些库设施不可用于所谓的独立实现)必须是自包含的。这就是为什么 C++ 没有等同于 Python 的eval
,也没有确定类成员等的方法,也没有其他需要执行环境的功能(或程序本身的大量开销而不是这样的环境)
For your individual questions:
对于您的个人问题:
- do you have to include the
<iostream>
everytime? Do you ever not need it?
- 你必须包括
<iostream>
每次吗?你永远不需要它吗?
#include <iostream>
is the directive that imports the <iostream>
header into your program. <iostream>
contains the standard input/output objects - in particular, cout
. If you aren't using standard I/O objects (for instance, you use only file I/O, or your program uses a GUI library, or are writing an operating system kernel), you do not need <iostream>
#include <iostream>
是将<iostream>
标头导入程序的指令。<iostream>
包含标准输入/输出对象 - 特别是cout
. 如果您不使用标准 I/O 对象(例如,您只使用文件 I/O,或者您的程序使用 GUI 库,或者正在编写操作系统内核),则不需要<iostream>
- same question for the standard library, when do you not need std::*?
- 标准库的相同问题,什么时候不需要 std::*?
std
is the namespace containing all of the standard library. using namespace std;
is sort of like from std import *
, whereas a #include
directive is (in this regard) more like a barebones import std
statement. (in actual fact, the mechanism is rather different, because C++ does not use using namespace std;
to automatically lookup objects in std
; the using-directive only imports the names into the global namespace.)
std
是包含所有标准库的命名空间。using namespace std;
有点像from std import *
,而#include
指令(在这方面)更像是准系统import std
语句。(实际上,机制是相当不同的,因为 C++ 不使用using namespace std;
自动查找 中的对象std
; using 指令仅将名称导入全局命名空间。)
I'll note here that using-directives (using namespace
) are frequently frowned upon in C++ code, as they import a lot of names and can cause name clashes. using-declarations (using std::cout;
) are preferred when possible, as is limiting the scope of a using-directive (for instance, to one function or to one source file). Don't ever put using namespace
in a header without good reason.
在这里我要指出,使用指令 ( using namespace
) 在 C++ 代码中经常不受欢迎,因为它们导入了很多名称并可能导致名称冲突。using std::cout;
如果可能,最好使用 using 声明 ( ),因为它限制了 using 指令的范围(例如,一个函数或一个源文件)。永远不要using namespace
在没有充分理由的情况下放入标题。
- is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
- “主要”部分是一个函数吗?你有没有调用过 main 函数?为什么是整数?为什么 C++ 需要有一个 main 函数而 Python 不需要?
main
is the entry point to the program - where execution starts. In Python, the __main__
module serves the same purpose. C++ does not execute code outside a defined function like Python does, so its entry point is a function rather than a module.
main
是程序的入口点 - 执行开始的地方。在 Python 中,该__main__
模块用于相同的目的。C++不像Python那样在定义的函数之外执行代码,所以它的入口点是一个函数而不是一个模块。
- do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
- 你需要“std::cout <<”吗?与 Python 相比,这不是不必要的冗长和复杂吗?
std::cout
is only needed if you don't import the cout
name into the global namespace, either by a using-directive (using namespace std;
) or by a using-declaration (using std::cout
). In this regard, it is once again much like the distinction between Python's import std
and from std import *
or from std import cout
.
std::cout
仅当您不cout
通过 using 指令 ( using namespace std;
) 或 using 声明 ( using std::cout
)将名称导入全局命名空间时才需要。在这方面,它再次很像 Python 的import std
和from std import *
或之间的区别from std import cout
。
The <<
is an overloaded operator for standard stream objects. cout << value
calls cout
's function to output value
. Python needs no such extra code because print
is built into the language; this does not make sense for C++, where there may not even be an operating system, much less an I/O library.
的<<
是用于标准流对象重载运算符。cout << value
调用cout
函数输出value
。Python 不需要这样的额外代码,因为print
它内置于语言中;这对 C++ 来说没有意义,因为 C++ 甚至可能没有操作系统,更不用说 I/O 库了。
- do you need to return 0 even when you are never going to use it?
- 即使您永远不会使用它,您是否也需要返回 0?
No. main
(and no other function) has an implicit return 0;
at the end. The return value of main
(or, if the exit
function is called, the value passed to it) is passed back to the operating system as the exit code. 0 indicates the program successfully executed - that it encountered no errors, etc. If an error is encountered, a non-zero value should be returned (or passed to exit
).
号main
(和没有其他功能)return 0;
在最后有一个隐含的。的返回值main
(或者,如果exit
函数被调用,则传递给它的值)作为退出代码传递回操作系统。0 表示程序成功执行 - 它没有遇到错误等。如果遇到错误,应该返回一个非零值(或传递给exit
)。
回答by Faxwell Mingleton
In response to your questions at the end of the post, it can be summed up with the philosophy of C++:
针对你在文末提出的问题,可以总结为C++的哲学:
You don't pay for what you don't use.
您不会为不使用的东西付费。
You don't always need to use stdin or stdout (Windows/GUI apps?), nor will you always be using the STL, nor will everything you write necessarily use the standard main (winAPI) etc. As a previous poster said, C++ is lower level than Python. You will be exposed to more of the details, which offers you more control over what you're doing.
您并不总是需要使用 stdin 或 stdout(Windows/GUI 应用程序?),您也不会总是使用 STL,您编写的所有内容也不一定使用标准 main (winAPI) 等。正如之前的海报所说,C++级别低于 Python。您将接触到更多细节,这使您可以更好地控制自己正在做的事情。
回答by Laurence Gonsalves
... do you have to include the everytime? Do you ever not need it?
...你必须包括每次吗?你永远不需要它吗?
You don't need it if you're not going to use iostreams in that module. In larger programs, few modules do any actual IO directly, and so few actually need to use iostreams.
如果您不打算在该模块中使用 iostreams,则不需要它。在较大的程序中,很少有模块直接执行任何实际的 IO,因此很少有模块真正需要使用 iostream。
Turning the question around: in python you need to import sys and/or os in most non-trivial programs. Why?
扭转问题:在python中,您需要在大多数重要程序中导入 sys 和/或 os 。为什么?
... same question for the standard library, when do you not need std::*?
... 标准库的同样问题,什么时候不需要 std::*?
You can have the using line or you can use the std:: prefix. This is very similar to the choice python gives you of either saying "from sys import *" or "import sys" and then having to prefix things with "sys.". In python you have to say "sys.stdout". Is "std::cout" really any worse?
您可以使用 using 行,也可以使用 std:: 前缀。这与 python 给你的选择非常相似,要么说“from sys import *”,要么说“import sys”,然后必须用“sys.”作为前缀。在 python 中,你必须说“sys.stdout”。“std::cout”真的更糟吗?
... is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
...“主要”部分是一个函数吗?你有没有调用过 main 函数?为什么是整数?为什么 C++ 需要有一个 main 函数而 Python 不需要?
Yes, main is a function. Typically you wouldn't call main yourself. The name "main" is reserved for the entry-point of your program. It returns an integer because the value returned is used as the status code of your program. In Python you can use sys.exit if you want to return a non-zero status code.
是的,main 是一个函数。通常你不会自己调用 main 。名称“main”是为程序的入口点保留的。它返回一个整数,因为返回的值用作程序的状态代码。在 Python 中,如果要返回非零状态代码,可以使用 sys.exit。
Python doesn't have the same convention because with Python you can have code in a module not in a function. This code is executed when you load the module. Interestingly, many people feel it is bad style to have code at the top-level of a module and will instead create a main function by doing something like this:
Python 没有相同的约定,因为使用 Python 您可以在模块中而不是在函数中使用代码。当您加载模块时执行此代码。有趣的是,许多人认为在模块的顶层编写代码是不好的风格,而是通过执行以下操作来创建主函数:
def main(argv):
# program goes here
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Also, in Python you tell the interpreter with module is the "main" module when you run it. eg: "python foo.py". In C, the "main" module is (effectively) the one with a function called main. (If there are multiple modules with a main function, it's a linker error.)
此外,在 Python 中,您在运行时告诉解释器模块是“主”模块。例如:“python foo.py”。在 C 中,“main”模块(实际上)是具有称为 main 的函数的模块。(如果有多个具有 main 函数的模块,则是链接器错误。)
... do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
...你需要“std::cout <<”吗?与 Python 相比,这不是不必要的冗长和复杂吗?
The equivalent in Python is actually "sys.stdout.write(...)". Python's print statement is a special-case short-hand.
Python 中的等效项实际上是“sys.stdout.write(...)”。Python 的打印语句是一种特殊情况的简写。
That said, many people do feel the iostreams convention of using bit-shifting operators for IO was a bad idea. Ironically, Python seems to have been "inspired" by this syntax. If you want to use print to write to somewhere other than stdout you can say:
也就是说,许多人确实认为将位移运算符用于 IO 的 iostreams 约定是一个坏主意。具有讽刺意味的是,Python 似乎受到了这种语法的“启发”。如果您想使用 print 写入 stdout 以外的其他地方,您可以说:
print >>file, "Hello"
... do you need to return 0 even when you are never going to use it?
...即使您永远不会使用它,您是否也需要返回 0 ?
You aren't going to use it, but your program will. As mentioned earlier, the value you return is the status code of your program.
你不会使用它,但你的程序会。如前所述,您返回的值是程序的状态代码。
Aside: I actually do feel that C++ is overcomplicated, but not because of any of the points you mention. All of the differences you mention go away (in the sense that you need just as much complexity in Python) once you start writing non-trivial programs that have multiple modules and do more than just writing to stdout.
旁白:我确实觉得 C++ 过于复杂,但不是因为你提到的任何一点。一旦您开始编写具有多个模块的非平凡程序并且不仅仅是写入标准输出,您提到的所有差异都会消失(从某种意义上说,您需要在 Python 中同样复杂)。
回答by jgottula
You include <iostream>
when you want to output things to the console. Since printing "Hello world" involves console output, you need iostream
.
您包括<iostream>
何时要将内容输出到控制台。由于打印“Hello world”涉及控制台输出,因此您需要iostream
.
The main
function is called by the operating system, basically. It gets called with the command-line arguments passed to the program. It returns an integer because the program must return an error code to the operating system (this is the standard way for determining if the last command was successful).
该main
函数基本上由操作系统调用。使用传递给程序的命令行参数调用它。它返回一个整数,因为程序必须向操作系统返回一个错误代码(这是确定最后一个命令是否成功的标准方法)。
You can always use printf("hello world");
instead of std::cout << "hello world";
if you want to go C style. It's a bit quicker to write and lets you do formatted output.
如果你想使用C 风格,你总是可以使用printf("hello world");
而不是std::cout << "hello world";
。编写起来要快一些,并且可以让您进行格式化输出。
You return 0
from main
to indicate that the program executed successfully.
你return 0
从main
表示程序执行成功。
The compiler does not automatically include all the standard libraries and use namespace std
because sometimes name collisions can result between your code and library code that you may not actually need at all. You don't always need all the libraries. Likewise, sometimes you are using a different main routine (Windows development comes to mind with its own, different WinMain
starting function). The compiler also does not automatically return 0
because sometimes the program needs to indicate that it completed unsuccessfully.
编译器不会自动包含所有标准库并使用命名空间,std
因为有时您的代码和您可能根本不需要的库代码之间会导致名称冲突。您并不总是需要所有的库。同样,有时您会使用不同的主程序(Windows 开发会想到它自己的不同WinMain
启动函数)。编译器也不会自动执行,return 0
因为有时程序需要指示它未成功完成。
回答by Bill Forster
There are good reasons for all these things. C++ is a very broad language it is used for everything from small embedded systems to giant applications built by 100s of programmers. The use case of a guy building a small program to run on a desktop is by no means the only one. So sometimes you are building library components. In that case no main(). Sometimes you are working on a tiny system with no standard library. In that case no std. Sometimes you want to build a Unix tool that works with other Unix text tools and signals its completion status with an int returned from main().
所有这些事情都有充分的理由。C++ 是一种非常广泛的语言,它用于从小型嵌入式系统到由数百名程序员构建的大型应用程序的所有内容。一个人构建一个在桌面上运行的小程序的用例绝不是唯一的用例。因此,有时您正在构建库组件。在那种情况下没有 main()。有时您正在一个没有标准库的微型系统上工作。在那种情况下没有标准。有时您想构建一个与其他 Unix 文本工具一起使用的 Unix 工具,并使用 main() 返回的 int 来指示其完成状态。
In other words the things you complain about are boilerplate to you. But they are vital details that vary to other users of the language.
换句话说,你抱怨的事情对你来说是样板。但它们是与该语言的其他用户不同的重要细节。
回答by Greg Hewgill
This reminds me of The Evolution of a Programmer. Some of the languages and technologies demonstrated are a bit dated now, but you should get the general idea. :)
这让我想起了程序员的进化。展示的一些语言和技术现在有点过时,但您应该了解总体思路。:)
回答by MSalters
One of the reasons C++ is rather complicated is because it was designed to address problems that crop up in large programs. At the time C++ was created as AT&T, their biggest C program was about 10 million lines of code. At that scale, C doesn't function very well. C++ addresses many of the problems you get with that kind of program.
C++ 相当复杂的原因之一是因为它旨在解决大型程序中出现的问题。在 C++ 被创建为 AT&T 时,他们最大的 C 程序大约有 1000 万行代码。在这种规模下,C 不能很好地发挥作用。C++ 解决了您在此类程序中遇到的许多问题。
With that said, it's also possible to answer the original questions:
话虽如此,也可以回答最初的问题:
- You would
include <iostream>
where it's needed. If you've got 10.000 C++ files, it's quite common that less than 1000, sometimes less than 100 will produce user-visible output. - A statement like
print "Hello, world"
assumes that there is a default output, but makes it hard to generalize. Thecout << "Hello, world"
form makes it explicit where the output goes, but the same form also allowscerr << "Goodbye, world"
andMyTmpFile << "Starting phase #" << i
- The standard library is in the
std::
namespace. My 10.000 files will be in an additional 25 namespaces. main
is an oddity in many ways, being the startup function.
- 你会
include <iostream>
在需要的地方。如果您有 10.000 个 C++ 文件,通常少于 1000 个,有时少于 100 个会产生用户可见的输出。 - 像这样的语句
print "Hello, world"
假设有一个默认输出,但很难概括。该cout << "Hello, world"
形式明确输出的去向,但同样的形式也允许cerr << "Goodbye, world"
和MyTmpFile << "Starting phase #" << i
- 标准库位于
std::
命名空间中。我的 10.000 个文件将位于另外 25 个命名空间中。 main
在很多方面都很奇怪,作为启动功能。
回答by pyon
Baldur:
博德:
You don't always need <iostream>
. The only things that you will always need are:
你并不总是需要<iostream>
. 您永远需要的唯一东西是:
- A
main
function (or aWinMain
, if you're writing Win32 apps). - Variables, functions, operators, language constructs (
if
,while
, etc.). - The ability to include functionality from libraries into your program.
- 一个
main
函数(或WinMain
,如果您正在编写 Win32 应用程序)。 - 变量,函数,操作符,语言构造(
if
,while
等)。 - 能够将库中的功能包含到您的程序中。
Everything else is application-specific.
其他一切都是特定于应用程序的。
As other posters say, the return value of the main
function is an error code1. If main
returns 0, be happy: everything worked OK!
正如其他海报所说,该main
函数的返回值是错误代码1。如果main
返回 0,请高兴:一切正常!
1This is useful when you write programs that "communicate" with other programs. The most simple way that a program can "tell" another whether it executed properly is using an error code.
1这在您编写与其他程序“通信”的程序时很有用。程序可以“告诉”另一个程序是否正确执行的最简单方法是使用错误代码。
回答by Stephen Veiss
As people have said, the simple answer is that they're different languages, with different goals. To answer your specific questions...
正如人们所说,简单的答案是它们是不同的语言,具有不同的目标。要回答您的具体问题...
... do you have to include the
<iostream>
everytime? Do you ever not need it?
...你必须包括
<iostream>
每次吗?你永远不需要它吗?
<iostream>
is one of the header files for iostreams, the part of the C++ standard library responsible for input/output; in this instance, you need it to gain access to std::cout
. If you're not doing I/O operations in a source file, you don't need to include it -- for example, most files containing class definitions probably won't need <iostream>
.
<iostream>
是iostreams的头文件之一,是C++标准库中负责输入/输出的部分;在这种情况下,您需要它来访问std::cout
. 如果您不在源文件中进行 I/O 操作,则不需要包含它——例如,大多数包含类定义的文件可能不需要<iostream>
.
... same question for the standard library, when do you not need std::*?
... 标准库的同样问题,什么时候不需要 std::*?
std
is the name of namespace containing classes in the standard library; it's there to avoid name collisions. Python has packages and modules to do this.
std
是标准库中包含类的命名空间的名称;这是为了避免名称冲突。Python 有包和模块可以做到这一点。
You can use the using
statement to bring items from another namespace into your current scope, see this FAQ entryfor an example (and an explanation of why it's bad to blindly bring all of std
into scope!).
您可以使用该using
语句将另一个命名空间中的项引入当前作用域,请参阅此 FAQ 条目以获取示例(并解释为什么盲目地将所有项std
引入作用域是不好的!)。
... why is the "main" part a function? Do you ever call the main function? Why is it an integer? Why does C++ need to have a main function but Python doesn't?
...为什么“主要”部分是一个函数?你有没有调用过 main 函数?为什么是整数?为什么 C++ 需要有一个 main 函数而 Python 不需要?
Executable statements in C++ have to be contained within a function, and the main
function is defined as where execution begins. In Python, executable statements can be placed at the top-level of a file, and execution is defined to .
C++ 中的可执行语句必须包含在函数中,main
函数被定义为执行开始的地方。在 Python 中,可执行语句可以放在文件的顶层,执行定义为 .
You can call main()
if you wish -- it's just a function, after all -- but there's not often a reason to do this. Behind the scenes, most implementations of C++ call main()
for you once some startup housekeeping has been done by the runtime library.
main()
如果您愿意,您可以调用——毕竟它只是一个函数——但通常没有理由这样做。在幕后,main()
一旦运行时库完成了一些启动内务处理,大多数 C++ 实现都会调用您。
The return value of main()
is returned back to the operating system. This stems from C and UNIX, in which application programs are required to provide a 1-byte exit status code, and returning that value from main()
is a clear way of expressing this.
的返回值main()
返回给操作系统。这源于 C 和 UNIX,其中要求应用程序提供 1 字节的退出状态代码,并且返回该值 frommain()
是一种明确的表达方式。
... why do you need "std::cout << "? Isn't that needlessly long and complicated compared to Python?
... 为什么你需要 "std::cout << "?与 Python 相比,这不是不必要的冗长和复杂吗?
This is just a design difference. iostreams is a fairly complex beast with lots of features, and one of the side-effects of this is that the syntax is a bit ugly for simple tasks at times.
这只是设计差异。iostreams 是一个相当复杂的野兽,具有许多功能,其副作用之一是有时对于简单任务来说语法有点难看。
... why do you need to return 0 even when you are never going to use it?
...为什么即使您永远不会使用它,也需要返回 0 ?
You do use it; this is the value returned to the operating system as the exit status of the program.
你确实使用它;这是作为程序退出状态返回给操作系统的值。
回答by Aziz
Python is high-levellanguage. C++ is middle-levellanguage.
Python是高级语言。C++是中级语言。