2012-02-22 16 views
1

私はこのプログラムをコンパイルして実行しようとしていますが、明らかに動作しません! leftaに** bottomは* leftaに変換できますか?彼らは間接のそのレベルで関係していないのでエラー: 'bottom **'から 'lefta **'への変換が無効

#include<iostream> 
using namespace std; 
class top 
{ 
private: 
    int a; 
public: 
    top(int b):a(b){} 
    virtual void output(){cout<<a<<endl;} 
}; 
class lefta:virtual public top 
{ 
private: 
    int b; 
public: 
    lefta(int c,int d):top(c),b(d){} 
    void output(){cout<<b<<endl;} 
}; 
class righta:virtual public top 
{ 
private: 
    int c; 
public: 
    righta(int c,int d):top(c),c(d){} 
    void output(){cout<<c<<endl;} 
}; 
class bottom:public lefta,public righta 
{ 
private: 
    int d; 
public: 
    bottom(int e,int f,int g,int h):top(e),lefta(e,f),righta(e,g),d(h){} 
    void output(){cout<<d<<endl;} 
}; 
int main() 
{ 
    bottom* bo=new bottom(1,2,3,4); 
// lefta* le=bo; 
// le->output(); 
    bottom** p_bo=&bo;//here 
    lefta** p_le=p_bo;//here 
    (*p_le)->output(); 
    return 0; 
} 
+7

。とにかくポインターへのポインターを持ってはいけません。 –

+1

より良い質問は、「ボトム*」が「レアナ*」に変換できるという理由だけで、「ボトム**」から「レアア**」にマジカルに当てはまるべきだと思いますか? –

+1

真剣に関連しているのは、 '' T ** ' - ' 'const T **'変換についての質問です(http://kera.name/articles/2009/12/a-question-on-indirect-constness /)。 –

答えて

5
class leftb : public lefta { /* blah */ }; 

bottom* bo = new bottom(1,2,3,4); 
bottom** p_bo = &bo; 
lefta** p_le = p_bo;// let's pretend it works 
// now p_le points to the variable bo, which is of type bottom* 
// so *p_le is a reference to the variable bo 
*p_le = new leftb(1,2); // wait, did we just assign a leftb* to a bottom*? 
// (and yeah, I'm leaking memory. Sue me) 
// bo now points to a leftb, but it is a bottom* 
// oops, we just broke the type system 
+0

+1一般に、 'X'が' Y'に変換されたということは、 'X *'が 'Y *'に変換できるという意味ではありません。この質問は、 'X = bottom *、Y = lefta *'の場合についてですが、ちょうどうまくいかない状況では、 'X = float、Y = double'を考慮してください。 floatをdoubleに変換するのは簡単ですが、 'float * 'を' double *'に変換するのはナンセンスです。型は同じサイズではなく、以前に 'float *'で保持されていたアドレスに 'double'値(' float'の範囲にないかもしれない)を格納することが何を意味するのかという問題はもちろんですが、 。後者は 'lefta * 'の問題です。 –

関連する問題