C++中的运行时多态性使用数据成员
我从在这里。
它说,使用数据成员在C ++中可以使用运行时多态性。
现在,考虑以下代码: -
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
Animal d1 = Animal();
cout<<d.color<<endl;
cout<<d1.color<<endl;
}
在上述颜色“黑色”上方的两种情况下都打印了。那么,这个运行时多态性的例子如何?
I was studying OOP from here.
It says that runtime polymorphism is possible in C++ using data members.
Now,consider this code:-
#include <iostream>
using namespace std;
class Animal { // base class declaration.
public:
string color = "Black";
};
class Dog: public Animal // inheriting Animal class.
{
public:
string color = "Grey";
};
int main(void) {
Animal d= Dog();
Animal d1 = Animal();
cout<<d.color<<endl;
cout<<d1.color<<endl;
}
In both the cases above the color "black" is printed. So, how is this example of runtime polymorphism ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不是运行时多态性的一个示例,而是对象切片。
这就是为什么a 好的C ++书籍这样的在线网站。
也就是说,首选/偏好应该始终是(假设您想对主题有深入的了解)a 好书 。然后,只有在您阅读本书中的主题后,您才能在网站上查找它以获取相同的实际示例。如果要引用合法C ++文档网站,则可以参考 cppReference href =“ https://www.learncpp.com/cpp-tutorial/virtual-functions/” rel =“ nofollow noreferrer”> nearchcpp 。这两个站点是C ++专用网站,因此您可以依靠那里给出的大多数信息/示例。建议先提及一本书。
It is not an example of runtime polymorphism but rather of object slicing.
This is one of the reason why a good C++ book is recommended over online sites like this.
That is, the first choice/preference should always be(assuming you want to have a deep understanding of the subject) a good book. And then only, after you've read up the topic in the book you can look it up on sites for practical examples of the same. If you want to refer to legit C++ documentation sites you can refer to cppreference and learncpp. These two sites are C++ dedicated sites so you can rely on most of the info/example given there. Again referring to a book first is recommended.
如果这是运行时多态性,则可以编写一个函数:
它将根据参数的动态类型打印对象的各个颜色。但是,没有C ++中的“基于成员变量的运行时 - 晶状体形态”之类的东西。教程是错误的,误导了。
如果编译并执行此操作:
输出将
没有虚拟成员变量。仅适用于虚拟成员函数使用虚拟调度:
output
将是具有成员变量的运行时多态性。此外,他们提出的示例还具有切片。请参阅此处:什么是对象切片?。
If this was runtime polymorphism you could write a function:
And it would print the respective color of the object based on the dynamic type of the parameter. However, there is no such thing as "Runtime-polymorphism based on member variables" in C++. The tutorial is wrong and misleading.
If compile and execute this:
The output will be
There is no such thing as virtual member variables. Only for virtual member functions use virtual dispatch:
Output:
The turial is wrong and misleading when it says that there would be runtime polymorphis with member variables. Moreover the example they present has object slicing. See here: What is object slicing?.