Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 指向多重继承中派生类的指针的指针_C++_Pointers - Fatal编程技术网

C++ 指向多重继承中派生类的指针的指针

C++ 指向多重继承中派生类的指针的指针,c++,pointers,C++,Pointers,我有3个类A、B和C。C是从A和B派生的。我得到指向C类指针的指针,并将其转换为A**,而B**,保存B**的变量的地址是A**在我的示例B**BdoublePtr中保存A**的地址。我使用以下代码 #include "conio.h" #include "stdio.h" #include "string.h" class A { public: A() { strA=new char[30]; strcpy(strA,"class A");

我有3个类A、B和C。C是从A和B派生的。我得到指向C类指针的指针,并将其转换为A**,而B**,保存B**的变量的地址是A**在我的示例B**BdoublePtr中保存A**的地址。我使用以下代码

#include "conio.h" 
#include "stdio.h"
#include "string.h"

class A
{
public:
    A()
    {
        strA=new char[30];
        strcpy(strA,"class A");
    }
    char *strA;
};


class B 
{
public:
    B()
    {
        strB=new char[30];
        strcpy(strB,"class B");
    }
    char *strB;
};

class C : public A, public B
{
public:
    C()
    {
        strC=new char[30];
        strcpy(strC,"class C");
    }
    char *strC;
};

int main(void)
{
    C* ptrC=new C(); 
    A * Aptr=(A*)ptrC; 
    printf("\n class A value : %s",Aptr->strA); 

    B * Bptr=(B*)ptrC;
    printf("\n class B value :%s",Bptr->strB);

    printf("\n\nnow with double pointer ");
    A ** AdoublePtr=(A **)&ptrC;
    Aptr=*AdoublePtr;
    printf("\n class A value : %s",Aptr->strA);

    B * * BdoublePtr=(B ** )&ptrC;
    Bptr=* BdoublePtr;
    printf("\n class B value : %s",Bptr->strB);

    getch();
    return 0;
}

问题是你想做的是不可能的;没有从
C**
B**
的有效转换。位于
*BdoublePtr
的指针包含a
C
的地址,而不是a
B
,您对
BdoublePtr
所做的任何操作都无法更改该地址

代码中的C样式转换相当于重新解释转换;它取
C*
的值,并假装它是a
B*
。这会产生未定义的行为。在您的例子中,
Bptr->strB
碰巧在
C
对象中的
A
对象中找到了指针指向的字符串,但原则上任何事情都可能发生


顺便说一下,如果你正在编写C++,那么你就应该使用C++头文件和字符串。这将首先修复代码中的一些内存泄漏。

能否在不使用额外html标记的情况下发布代码,并将代码缩进四个空格或按“代码”按钮使其显示为格式?请在问题中提出一个问题。我在这里看不到问题,但是将C样式转换与多重继承结合使用几乎肯定会出错。使用
static\u cast
dynamic\u cast
代替。我已经用static\u cast和dynamic\u cast检查了cast,得到了与上面相同的结果