我定义了一个名为 Polygon 的抽象基类,它包含一个签名如下的方法
int operator==(Polygon other)
编译时出现错误
cannot declare parameter ‘other’ to be of abstract type ‘Polygon’
这是预料之中的,因为多边形是一个抽象类,不能有对象。但是,当我用“&other”替换“other”时,编译的代码甚至给出了预期的结果。
从有关堆栈溢出的其他帖子中,我了解到,当我定义一个函数时,其参数前面带有“&”,则会创建传递参数的别名。现在我有一个名为“其他”的“多边形”类型的变量,它不仅仅是一个指针。多边形是 ABC,怎么会发生这种情况?从标准的角度来看,这样的代码是否有效?
最佳答案
From other posts on stack overflow I understood that when I define a function with paremeters preceded by '&' an alias to the passed argument is created.
正确的术语是“引用”而不是“别名”(这在 C++ 中意味着不同的东西)。
Now I have a variable called 'other' of type 'Polygon', which is not just a pointer.
不,other
的类型是Polygon&
,即引用- Polygon
.你是对的,它不是一个指针,但在很多方面它的行为就像一个指针。指针和引用之间的主要区别在于引用永远不能指向任何内容(而指针可以),并且引用一旦创建就不能更改为指向不同的内容。
How can this happen as Polygon is an ABC?
Polygon
是一个抽象基类,所以你不能自己创建一个。但是假设你有一个像 Rectangle
这样的具体类继承自 Polygon
.当您将矩形实例传递给 operator==(Polygon& other)
时,您正在引用 Polygon
在 Rectangle
, 这很好。
Is such code valid from a standards point of view.
这种类型的“引用多态性”不仅有效,而且对于 C++ 的工作方式也是绝对必要的。
关于c++ - 将引用作为参数传递给抽象类中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26326628/