将对象强制转换为数据类型
Cast an object to a data type?
如何将对象强制转换为数据类型,比如int/string?以下是示例代码:
我希望能够将以下add与integers
和var
一起使用示例var = <expression> + <expression> ; //expression can be int or var
这是var的代码:
#pragma once
#include <string>
class vars
{
public:
vars(std::string Name):name(Name){value = 0;}
void setValue(int val);
int getValue(void) const;
// std::string getName(void) const;
~vars(void);
private:
std::string name;
int value;
};
这是添加的代码:
#pragma once
#include "action.h"
#include "vars.h"
class add: public action
{
public:
add(vars& v, int s1, int s2):target(v),source1(s1),source2(s2){} //downcast the vars to int if needed, how to do so explicitly?
virtual void excute ();
~add(void);
private:
vars& target; //not sure of it
int source1, source2;
};
如果您有一个只接受一个参数的构造函数(在本例中为int
),则该参数的类型可以隐式转换为vars
类型的临时对象。然后,您只需为vars
重载operator+
。
vars(int a); // Add this constructor
vars & operator+=(const vars other) {
value += other.value; // Or some other operations
return *this;
} // This as memberfuncion inside the vars class
vars operator+(vars left, const vars & right) {
return left += right;
} // This outside the class
这是直接的解决方案。
最好将只有一个参数的构造函数定义为explicit
,以避免不必要的隐式转换。但如果这是你想要的,你也可以不用它。
另一种情况是,您希望获得int
(或某些其他类型)作为结果,这可以通过重载operator
类型来解决。例如:
explicit operator int() { return value; } // Inside class definition
// Which is called like:
vars var("meow");
auto sum = 1 + int(var); // The C-Style
auto sum = 1 + static_cast<int>(var); // The better C++ style
同样,explicit
是可选的,但节省。
相关文章:
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- 从 cpp lib 调用函数时的数据类型转换
- 如何将两个 jlong 数据类型转换为 jstring,然后将两个字符串连接在一起以便从 JNI 将字符串返回给 jav
- pybind11:Python 到 C++ 数据类型转换不起作用
- 尝试执行绕道附加,但无法将我的lua函数的数据类型转换为LPVOID
- 使用正确的数据类型转换java中的c++方法逻辑
- XLL由XLW制造,BOOST UBLAS MyMatrix数据类型转换为双**失败
- 将原始数据类型转换为空隙指针类型
- 为什么数据类型转换错误只出现在C++中而不出现在C中
- 正在尝试将time_t数据类型转换为(dd/mm/yyyy)格式C++
- C++中的类到类数据类型转换
- C++ 中的数据类型转换
- 无法从一种数据类型转换为相同的数据类型?
- 内置数据类型转换为用户定义的数据类型c++
- 如何将c数据类型转换为neon数据类型
- 将内置数据类型转换为std::string: memcpy vs snprintf
- c++中的动态数据类型转换
- 如何将Mat数据类型转换为无符号短指针
- 将c++的变量数据类型转换为c#