将对象强制转换为数据类型

Cast an object to a data type?

本文关键字:数据类型 转换 对象      更新时间:2023-10-16

如何将对象强制转换为数据类型,比如int/string?以下是示例代码:

我希望能够将以下add与integersvar一起使用示例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是可选的,但节省。