C ++隐式类型转换

时间:2013-12-29 00:59:54

标签: c++ type-conversion operator-keyword

我想将许多相似的类转换为彼此。它们至少有一个共同的抽象祖先,它定义了两种基本方法。

我遇到了奇怪的类型转换错误,所以我做了一个简化的例子。在层次结构的顶部:Integer类。它是一个具有int val()方法的抽象类。其中一个孩子只是物理int值的持有者,而另一个引用2个整数,val()是其两个引用的整数的总和。

我编写了这段代码,我无法理解为什么注释表达式无法编译,而使用临时变量的工作效果很好。

class Sum;

class Integer {
    public:
        virtual int val(void) const = 0;
        Sum operator+(Integer & other);
};

class Sum : public Integer {
    private:
        Integer &op1, &op2;
    public:
        explicit Sum(Integer &a, Integer &b) : op1(a), op2(b) {};
        int val(void) const {return op1.val() + op2.val();};
};

class Int : public Integer {
    private:
        int v;
    public:
        Int(int value=0) : v(value) {};
        Int(Integer & other) : v(other.val()) {};
        int val() const {return v;};
        Int & operator=(Integer & other){v = other.val(); return *this;};
        Int & operator=(int value){v = value; return *this;};
};

std::ostream & operator<<(std::ostream & out, Integer & i){return out << i.val();}
Sum Integer::operator+(Integer & other){return Sum(*this, other);}

int main(int argc, const char **argv){
    Int a=42, b=57;
//  Int s = a+b; => conversion from ‘Sum’ to non-scalar type ‘Int’ requested
    Sum r = a+b;
    Int s = r;       /* OK */
    cout << a << " + " << b << " = " << s << endl;
    return 0;
}

2 个答案:

答案 0 :(得分:2)

对于采用非const引用的函数(如Int的构造函数),不能传递临时对象。对此的一个常见解释是因为如果一个函数采用非const引用,则允许修改引用对象,但是对于临时对象,由于引用变量不能在外部访问,因此这种更改实际上并不存在。函数调用。

正如DyP在评论中建议的那样,将值更改为const将提供解决方案,或者您可以简单地将其绑定到变量,就像使用'Sum r = a + b'一样。

答案 1 :(得分:2)

class Int : public Integer {
    private:
        int v;
    public:
        Int(int value=0) : v(value) {};
        Int(Integer & other) : v(other.val()) {};
        int val() const {return v;};
        Int & operator=(Integer & other){v = other.val(); return *this;};
        Int & operator=(int value){v = value; return *this;};
};

构造函数Int(Integer & other)不会修改其参数,因此可以(应该)生成该引用const

Int(Integer const& other) : v(other.val()) {};

这也解决了您的问题:

Sum Integer::operator+(Integer & other);
Int s = a+b;

operator +(应该可以说是自由函数而不是成员函数)返回Sum类型的prvalue / temporary。此临时无法绑定到非const左值引用,因此无法使用构造函数Int(Integer & other)

类似于Int & operator=(Integer & other),const引用就足够了。