0

Cell私は、ここで定義と呼ばれるテンプレートクラスを持っています:

template <class T>
class OneCell
{
.....
}

CellここにからTまでのキャスト演算子があります

virtual operator const T() const
{
   .....
}

今、私はDCellここ でと呼ばれるクラスを派生させました

template <class T>
class DCell : public Cell<T>
{
.....
}

セルのキャスト演算子をオーバーライドする必要があります(ifを少し挿入します)が、セルのキャスト演算子を呼び出す必要があります。他の方法では、次のようになります

virtual operator const T() const
{
    if (...)
    {
        return Cell<T>::operator const T;
    }
    else throw ...
}

しかし、コンパイラエラーが発生しました

エラー:タイプ'const int(Cell ::)()const'の引数が'constint'と一致しません

私に何ができる?

ありがとう、そして私の貧弱な英語について申し訳ありません。

4

4 に答える 4

3

括弧がないため、コンパイラーは、メンバー関数を呼び出そうとしているのではなく、メンバー関数を返そうとしていると考えました。

        return Cell<T>::operator const T();
于 2012-06-19T21:19:53.573 に答える
2

あなたは実際にオペレーターを呼んでいません:

return Cell<T>::operator const T();

完全なコード:

template <class T>
class OneCell
{
public:
    virtual operator const T() const
{
        return T();
    }
};

template <class T>
class DCell : public OneCell<T>
{
public:
    virtual operator const T() const
    {
        cout << "operator called";
        return OneCell<T>::operator const T();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    DCell<int> x;
    int y = (int)x;
}
于 2012-06-19T21:19:46.827 に答える
1

Cellとの実装でこのコードを検討してくださいDCell

#include <iostream>
#include <exception>

template<class T>
class Cell
{
protected:
    T cnt;
public:
    Cell(const T& cnt = T()) : cnt(cnt){}
    virtual operator const T() const { return cnt; }
};

bool test_bool = true;

template<class T>
class DCell : public Cell<T>
{
public:
    DCell(const T& cnt = T()) : Cell<T>(cnt){}
    virtual operator const T() const
    {
        if(test_bool)
        {
            return Cell<T>::operator const T(); // Here you had Cell<T>::operator const T;
        } else {
            throw std::exception();
        }
    }
};

int main()
{
    DCell<int> cell(5);
    std::cout << static_cast<int>(cell) << "\n"; // prints 5 (and a new line)
    return 0;
}
于 2012-06-20T12:19:18.613 に答える
0

オペレーターを仮想化しないでください。protected virtual代わりに、ヘルパー関数に委任してください。

template <class T>
class Cell
{
    public:
        operator const T() const { return cvt_T(); }
    protected:
        virtual const T cvt_T() const;
};

template <class T>
class DCell : public Cell<T>
{
    const T cvt_T() const
    {
        if (...)
        {
            return Cell<T>::cvt_T();
        }
        else throw ...
    }
};

これと他の良い習慣はGotWから学ぶことができます、ここに仮想アーキテクチャに関するセクションがあります

于 2012-06-19T21:15:58.853 に答える