根据 What is a Class and Object in C++?
A Class is like a blueprint, an object is like a house built from that blueprint.
You can have many houses with the same layout/floorplan (read class), but each is it's own instance (read object). Each has it's own owner, furniture, etc.
Note that there are also objects whose blueprint is not a class (e.g. integers).
总而言之,有不同类型的对象(例如 int、float 等)。您可以创建用户定义的类型,称为“类”。
在 C++ 中,术语对象用于任何类型的实例,包括类和基本类型。
然而,根据http://www.cplusplus.com/doc/tutorial/classes/
An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable.
这个说法是不是不准确?对象可以是类的实例,但也可以是基本类型的实例。
那什么是实例化呢?
创建基本类型的实例(例如 int x = 3;
)是否被视为“实例化”?因为它在技术上创建了一个类型的实例。
最佳答案
对象是类型的实例。
继续您的问题:
Isn't that statement (the cppreference one) inaccurate ? An object could be an instantiation of a class, but it could also be an instance of a fundamental type.
你是对的。
Also, wouldn't creating an instance of a fundamental type (ex. int x = 3;) be considered "instantiation"? Since it is technically creating an instance of a type.
再一次,正确。
个人建议:不要太担心确切的定义,把精力更多地花在“通过编写代码来学习”上
how is instantiation defined?
好吧,既然你这么坚持,那我就客气地反驳一下:
您在网上或书籍中找到的所有定义都不是权威的。这些事情的唯一权威是 C++ 标准:看这里:N4713 .如您所见,该标准过于技术化,难以解析和理解。之所以这样,是因为它绝不是为了学习,而是为了彻底、明确地定义语言的句法和语义。这是编译器实现者在编写编译器时转向的文档,您可以使用它来将漂亮的 C++ 源代码转换为机器代码。
由于该标准不是学习 C++ 的方法,因此每个人都提出了自己的定义和术语,以便更轻松地传达有时更复杂的问题。这样做时,有时您看到的定义不完整,或略有错误,或不适用于奇怪的极端情况。您会发现不同作者使用的相同术语略有不同。这是坏事吗?也许吧,但幅度不大。学习时,掌握简单的概念和工具非常重要,这样您才能一步一个脚印。恕我直言,失去“严谨彻底”是一个很小的代价,但我明白这对于那些非常认真地对待学习 Material 中的每一个词的人来说是多么的困惑。
回到你的问题:在标准中,据我所知,术语“实例化”并未在这个意义上使用,它用于“模板实例化”,这是另一回事。
不过没关系,我们不需要标准来理解一个简单的概念。对于您的上下文,实例化是对象的创建。这是一个非常简单的概念,不要想太多。
C++ 标准将“实例化”用于不同的目的,但您仍然可以理解这个概念。如果您愿意,可以将其命名为其他名称。
关于c++ - 对象的定义和实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57618492/