无法将派生类对象分配给基类指针 [英] Unable to assign derived class object to base class pointer

查看:81
本文介绍了无法将派生类对象分配给基类指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,专家,

我正在以保护模式从A类继承B类.但是我无法将派生类对象分配给基类指针为

Hi Experts,

I am inheriting class B from class A in protected mode. But I am unable to assign the derived class object to the base class pointer as

A *ptr;
    B b(30,50);
    ptr=&b;



在私有模式继承中也会发生相同的问题.但是,如果我们在公共模式下继承它,那么一切都会好的.我想念的是什么?任何的想法.?请帮我.

我的代码




The same issue is happened in private mode inheritance.But if we inherit it in public mode then everything is ok. What I am missing.? Any idea.? Please help me on this.

My code


#include <stdafx.h>
#include <iostream>
#include <fstream>
#include <assert.h>
#include <cassert> // for assert()
using namespace std;

class A
{
public:
int a;
    A(int t)
    {
        a=t;
    }
     void Fun_A()
    {
    cout<<"Class A Fun()"<<a;

    }



};



class B: protected A // Private mode has the same problem But in public mode it is ok

{

    public:

    int b;

    B(int t,int x):b(t),A(x)

    {



    }



};



void main(void)

{

    A *ptr;

    B b(30,50);

    ptr=&b;



}





谢谢
Arun





Thanks
Arun

推荐答案

发生此错误的原因是,当派生为protected或private时实例化该对象的任何人都不能访问该基类.可以像其他人建议的那样通过类型转换覆盖此行为,但是不建议这样做,这是预期的行为.

在这里看到一个很好的解释:
http://vapvarun .com/study/softE/john%20wiley%20and%20sons%20-%20programming%20with%20object-oriented%20programming/5399final/lib0164.html [
The reason for this error is because the base class should not be accessible by whomever instantiates the object when derived as protected or private. This behavior can be overriden by typecasting as others have suggested, but it is not recommended and is expected behavior.

See a good explanation here:
http://vapvarun.com/study/softE/john%20wiley%20and%20sons%20-%20programming%20with%20object-oriented%20programming/5399final/lib0164.html[^]

If you want to access the base pointer, then you want a public derivation.


我认为您遇到错误C2243.
由于您是在保护模式下继承A的,因此您无法从B类访问A类零件.请查看链接以获取更多信息.

Msdn(错误信息):
http://msdn.microsoft.com/en-us/library/s5480d1f.aspx [ ^ ]

Stackoverflow:
http://stackoverflow.com/questions/1471800/getting-rid-of-error-c2243 [^ ]
I think you are getting error C2243.
Since you are inherited A in protected mode you can not access the Class A part from Class B.Check the links for more info.

Msdn(Error info):
http://msdn.microsoft.com/en-us/library/s5480d1f.aspx[^]

Stackoverflow:
http://stackoverflow.com/questions/1471800/getting-rid-of-error-c2243[^]


错误没有错误C2243出现很多类型转换问题
您可以尝试如下
Error no error C2243 comes for lots of Typecasting issues
You may try like follows
A *ptr;
B *b(30,50);
ptr=(A*)b;


这篇关于无法将派生类对象分配给基类指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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