2010-06-18 63 views
-3

我有3个类A,B和C. C是从A和B派生的。我得到指向C类指针的指针并将其转换为A **,并且B * *,即保持了B中的变量**有**的在我的例子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; 
} 
+3

你可以发布你的代码没有额外的HTML标记,并缩进它所有的四个空格或按代码按钮,使其显示格式? – 2010-06-18 10:11:18

+3

在您的问题中提出问题。 – 2010-06-18 10:11:31

+2

我在这里没有看到任何问题,但是将C风格演员与多重继承结合使用几乎肯定会出错。改为使用'static_cast'或'dynamic_cast'。 – 2010-06-18 10:14:26

回答

2

的问题是你试图做的事情是不可能的;没有从C**B**的有效转换。 *BdoublePtr上的指针包含C的地址,而不是B,并且您没有做任何事情可以更改该地址BdoublePtr

代码中的C风格等效于reinterpret_cast;它取值C*并假设它是B*。这给出了未定义的行为。在你的情况下,Bptr->strB恰好在指针指向的C对象中找到A对象中的字符串,但原则上绝对会发生任何事情。顺便说一下,如果你正在编写C++,那么你真的应该使用C++头文件和字符串。这将解决你的代码中的一些内存泄漏问题。