OOPS相关的与禁欲有关的疑问 [英] OOPS related doubt related to inhetitence

查看:151
本文介绍了OOPS相关的与禁欲有关的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对OOPS有一个疑问. 为什么我们需要将基类对象指向派生类.我们可以直接创建派生类对象并可以执行所需的操作.(据我了解)

例如

I have one doubt related to the OOPS. Why we need to point base class object to the derived class. We can directly create derived class object and can perform required operation.(as per my understanding)

E.g.

public class abc
    {
        public int abc123 = 0;
        public void qwerty()
        {
            MessageBox.Show("from base");
        }
    }
    public class pqr:abc
    {
        public int pqr123 = 0;
        public void qwerty123()
        {
            MessageBox.Show("from derived");
        }
    }



在上面的示例中,如果我们添加



In above example if we add

abc qw = new pqr();

我们无法访问派生的类成员.

如果您对此有任何想法,请告诉我.

we can not access derived class members.

Please let me know if you have any idea about it.

推荐答案

abc qw = new pqr();


因为,尽管您创建了pqr类型的对象,却将其分配给了abc类型的对象.因此,您告诉编译器您将仅访问abc类型可访问的属性. Bjarne Stroustrup的 C ++页面 [ ^ ].


Because, although you have created an object of type pqr you have assigned it to an object of type abc. So, you are telling the compiler that you will only access properties that are accessible to an abc type. This is a language restriction which is described in Bjarne Stroustrup''s C++ page[^].


接受6票否决投票


如果我告诉您我有一只狗,您可以放心地假设我有一只狗.

如果我告诉你我有一只宠物,那么你不知道那只动物是狗,可能是猫,甚至是长颈鹿.不知道一些额外的信息,就无法安全地假设我有一只狗.

类似地,派生对象是基类对象(作为其子类),因此可以由基类指针指向.但是基类对象不是派生类对象,因此不能分配给派生类指针.

(您会听到的吱吱声是类比拉伸)

假设您现在想给我买宠物的礼物.

在第一种情况下,您知道它是狗,可以给我买皮带,每个人都很高兴.

在第二种情况下,我没有告诉您我的宠物是什么,因此,无论如何如果您要给我买礼物,您需要知道我没有告诉过您的信息(或只是猜测),如果您购买了皮带,我真的有一只狗,每个人都很高兴.

但是,如果我实际上有一只猫,那么我们现在知道您做了一个错误的假设(预测),并且在皮带上有一只不快乐的猫(运行时错误)
6 down vote accepted


If I tell you I have a dog, you can safely assume that I have a dog.

If I tell you I have a pet, you don''t know if that animal is a dog, it could be a cat or maybe even a giraffe. Without knowing some extra information you can''t safely assume I have a dog.

similarly a derived object is a base class object (as its a sub class), so can be pointed to by a base class pointer. however a base class object is not a derived class object so can''t be assigned to a derived class pointer.

(The creaking you will know hear is the analogy stretching)

Suppose you now want to buy me a gift for my pet.

In the first scenario you know it is a dog, you can buy me a leash, everyone is happy.

In the second scenario I haven''t told you what my pet is so if you are going to buy me a gift anyway you need to know information I havent told you (or just guess), you buy me a leash, if it turns out I really did have a dog everyone is happy.

However if I actually had a cat then we now know you made a bad assumption (cast) and have an unhappy cat on a leash (runtime error)


这篇关于OOPS相关的与禁欲有关的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆