小编Jer*_*sen的帖子

为什么C++选择将返回值强制转换为int?

由于各种无聊的原因,我需要一个盒装的int类,它主要作为一个int,但是是一个继承自base的类,因此它可以与对象层次结构的其他部分一起工作.我包含了一个构造函数,它接受一个int,以及一个int cast,所以我可以很容易地将我的盒装int与代码中的常规int混合.但是,我看到一个非常奇怪的行为,我无法弄清楚:当我从函数返回我的盒装int时,我希望它使用我的复制构造函数来引用另一个BoxedInt.但是,它将我的盒装int转换为int,然后使用我的int构造函数.这会导致问题,因为在我的实际代码库中,在这种情况下我还想要复制其他基类属性,并且通过获取此强制转换/构造函数路径它们会丢失.这是有问题的代码:

class BoxedInt
{
private:
    int m_int;
public:
    BoxedInt():m_int(0)
    {
        trace(L"Constructed with nothing");
    }

    BoxedInt(int val):m_int(val)
    {
        trace(L"Constructed with int");
    }

    BoxedInt(BoxedInt& val)
    {
        trace(L"Constructed with reference");
        m_int = val.m_int;
    }

    operator int()
    {
        trace(L"Cast to int");
        return m_int;
    }
};

BoxedInt funky()
{
    BoxedInt TempInt = 1;
    return TempInt;
}

int main(int argc, char* argv[])
{
    trace(L"Start");
    BoxedInt test1 = 1;
    trace(L"Copying");
    BoxedInt test2 = test1;
    trace(L"Assigning from return value");
    BoxedInt test3 = funky();
    trace(L"Done");
    return 0;
} …
Run Code Online (Sandbox Code Playgroud)

c++ constructor casting reference copy-constructor

2
推荐指数
2
解决办法
265
查看次数

标签 统计

c++ ×1

casting ×1

constructor ×1

copy-constructor ×1

reference ×1