在C++中,需要使用分号结束类定义。我想知道为什么C#不需要它?

最佳答案

C++语言允许在类声明中声明变量。相似:

class Mumble {
  // etc...
} globalMumble;

分号是必需的语法,以使编译器知道是否也声明了变量。此语法是很难解释编译错误消息的长期来源。最糟糕的是:

mumble.h:
class Mumble {
  // etc...
}      // <== note: semi-colon forgotten

mumble.cpp:
#include "stdafx.h"
#include "mumble.h"

int main() {
    Mumble* obj = new Mumble;
}

这将产生以下美妙的错误消息:
main.cpp(8): error C2628: 'Mumble' followed by 'int' is illegal (did you forget a ';'?)
main.cpp(9): error C3874: return type of 'wmain' should be 'int' instead of 'Mumble'
main.cpp(10): error C2440: 'return' : cannot convert from 'int' to 'Mumble'

请注意,所有错误消息均引用.cpp文件,而不是包含错误的.h文件。绝望的程序员为此付出了很多时间,还有大量的头发。

C#语言是由熟练的C++程序员设计的。谁开始设计一种语言来避免这类现实生活中的语法问题。这在C#语法的许多地方都显而易见。长话短说:C#不允许这种C++语法,不需要分号来帮助编译器。

10-02 14:49