分配变量和类的类型

Assign type of variable and class

本文关键字:类型 变量 分配      更新时间:2023-10-16

请帮帮我,让我问一个愚蠢的问题。我将变量x声明为DeriveType (DeriveType是一个类)。我想把y赋值给x,例如y = x但是当我编译时,编译器显示了错误错误:无法将"const派生类型"转换为"int"请告诉我如何解决这个问题。非常感谢。你的真诚,

这是类派生类型

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 = %fn", *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].

我的想法是如何从派生类型转换为double/int,反之亦然。

谢谢你的阅读和帮助。

我非常感谢你的提示。

你的真诚

非常感谢

如果将类型转换为int有意义,则可以提供转换操作符:

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

如果没有意义,那么就不要写这样的代码