簡體   English   中英

C ++轉換派生類

[英]C++ conversion derived classes

我的代碼有問題(c ++)。 我試着解釋一下我需要什么。 我有一個基類模板和兩個方法不同的繼承類。 對於每個繼承的類,我需要創建在另一個類中轉換類的構造函數/方法。 指出錯誤。

template < typename T > class A{

protected:
    T **m;

    void allocate_mem(T ***ptr){
        *ptr = new T*[1];
        (*ptr)[0] = new T[1];
    }

public:

    A(){
        throw logic_error("Error!");
    }

    void renew(T val){
        m[0][0] = val;
    } 

    ~A(){
        delete[] m[0];
        delete[] m;
    }

        T say_elem(){
        return m[0][0];
    }

};

template < typename T > class B: public A< T >{

public:

    B(int val){
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = val;
    }

    B(const C &c){    //'C' does not name a type
                      //ISO C++ forbids declaration of 'c' with no type [-fpermissive]
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = A<T>::c.say_elem();
    }

};

template < typename T > class C: public A< T >{

public:

    C(double val){
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = 1;
    }

    C(const B &b){    //'B' does not name a type
                      //ISO C++ forbids declaration of 'b' with no type [-fpermissive]
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = A<T>::b.say_elem();
}
};

我該怎么辦? 謝謝您的幫助!

要修復“不要命名類型”錯誤,請嘗試向前聲明您的類(即,將以下行放在文件的頂部)。

template < typename T > class A;
template < typename T > class B;
template < typename T > class C;

然后將此: B(const C &c)更改為: B(const C<T> &c) ,對於C構造函數也是如此。

以下代碼為我編譯:

template < typename T > class A {
protected:
    T **m;
    void allocate_mem(T ***ptr){
        *ptr = new T*[1];
        (*ptr)[0] = new T[1];
    }

public:
    A() { throw logic_error("Error!"); }
    void renew(T val) { m[0][0] = val; } 
    ~A() {
        delete[] m[0];
        delete[] m;
    }

    T say_elem() { return m[0][0]; }
};

template < typename T > class C;
template < typename T > class B: public A< T >{
public:

    B(int val) {
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = val;
    }

    B(const C<T> &c) {
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = A<T>::c.say_elem();
    }
};

template < typename T > class C: public A< T >{
public:
    C(double val) {
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = 1;
    } 

    C(const B<T> &b) {
        A<T>::allocate_mem(& this->m);
        A<T>::m[0][0] = A<T>::b.say_elem();
    }
};

前向聲明的答案幾乎是正確的,但前向聲明不能指定父類。 轉發聲明如下:

template < typename T > class A;
template < typename T > class B;
template < typename T > class C;

您的類之間存在一些循環依賴關系。 至少你需要提供一些類的前向聲明。 即便如此,由於方法聲明順序,您可能需要更改對指針的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM