2015-05-28 84 views
-3

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

这是类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

应该从“DeriveType”转换为“int”是什么意思?你应该写一个转换操作符。 – TartanLlama

回答

0

如果是有意义的你的类型转换为int,那么你可以提供一个转换操作符:

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

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

+0

感谢您的回复。你是个好人。 – nothingx0x

+0

尊敬的专业人士,我如何使用你的命中,我不能使用:int y =(int)x;它不起作用 – nothingx0x

+0

@ nothingx0x:如果转换有意义,那么您必须添加转换运算符,正如我所说的。如果没有意义,那就不要试图去做,正如我所说的那样。 –