分配变量和类的类型
Assign type of variable and class
请帮帮我,让我问一个愚蠢的问题。我将变量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=∑ [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>;}
//...
};
如果没有意义,那么就不要写这样的代码
相关文章:
- 从模板创建通用打印函数,以打印基元数据类型变量的值
- 指针数据类型变量如何包含对象?
- 将 static_cast<int>(-15) 分配给静态常量字符类型变量
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- 如何为结构类型变量赋值
- 如何将字符类型变量附加到字符串中?
- 共享或私有 openmp 代码中的结构化类型变量
- 有没有办法在 c++ 中制作类型变量?
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 如何检查类中定义的枚举类型变量是否被分配给?
- 将子类实例保存在父类型变量中并通过父变量使用 Child 函数?
- 是否可以在没有结构的情况下创建新的类型变量?
- 为什么类型变量;不调用默认 CTR
- 如何使用CIN将输入整数值获取到char类型变量中
- 如何为 char** 类型变量提供适当的值,以便将其分配给字符串变量
- 在C++标准中哪里说必须初始化 const 内置类型变量的定义
- 为什么可以将其他类型变量用作C 中常量参考参数参数的参数
- Eclipse CDT 打开声明的自动类型变量
- 如何计算长长类型变量中的位数
- 将自动类型变量初始化为零.这种类型安全吗?