分配变量和类的类型

时间:2015-05-28 14:27:41

标签: c++

请帮助我,让我问一个愚蠢的问题。 我将变量x声明为DeriveType(DeriveType是一个类)。 我想将一个int y分配给x,例如 int y = x 但是当我编译时,编译器会显示错误 错误:无法转换' const DerivType'到' int' 请告诉我如何解决这个问题。 非常感谢你。 您诚挚的,

这是Class DerivType

class DerivType;

typedef DerivType (*ddf_FctPtr)(const DerivType&);

class DerivType { private: interval f, df, ddf;

public: DerivType ( ); 
DerivType ( const interval&, const interval&, const interval& ); 
DerivType ( const DerivType& );

DerivType& operator= ( const DerivType& );

friend DerivType DerivConst ( const real& );
friend DerivType DerivConst ( const interval& );
friend DerivType DerivVar   ( const real& );
friend DerivType DerivVar   ( const interval& );

friend inline const interval fValue   ( const DerivType& );  
friend inline const interval dfValue  ( const DerivType& );  
friend inline const interval ddfValue ( const DerivType& );  

friend DerivType operator+ ( const DerivType& );
friend DerivType operator- ( const DerivType& );

.... 

我有一个喜欢这个的功能。

DerivType f ( const DerivType& x )
{
        DerivType result;
        DerivType xx;
        double sum;
        xx = x;
        //Convert x from DerivType to double
        void *pVoidx = &xx;                                     [1]
        double *pDoublex = static_cast<double*>(pVoidx);        [2]
        MLPutReal(lp, *pDoublex);

        MLGetReal(lp, &sum);

        //Convert from double to DerivType for the return value of function
        printf( "x = %f, result = %f\n", *pDoublex, sum);
        void *pSum=&sum;                                            [3]
        DerivType *pDerivTypeSum = static_cast<DerivType*>(pSum);   [4]
    return *pDerivTypeSum;
}

此功能正常。但我的老师说这不是好的代码,因为即使代码在这种情况下工作,它依然依赖于实现和体系结构。 (他给我链接:http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=195[ ^])

你能帮助我改进这段代码,即[1],[2],[3],[4]。

我的想法是如何将DerivType转换为double / int,反之亦然。

感谢您的阅读和帮助。

我非常赞赏你的提示。

您诚挚的

非常感谢你 您诚挚的,

1 个答案:

答案 0 :(得分:0)

如果将类型转换为int是有意义的,那么您可以提供转换运算符:

class DeriveType {
    //...
    operator int() {return <some integer value>;}
    //...
};

如果它没有意义,那么就不要编写试图这样做的代码。

相关问题