内置数据类型转换为用户定义的数据类型c ++

时间:2011-12-20 07:31:38

标签: c++

我的问题是关于c ++中的数据类型转换。 c ++是否为内置数据类型(int,float)提供了对用户定义数据类型的隐式转换?

在下面的例子中,我试图添加一个带有测试对象类型的double(t4 = t3 + 1.0),并且使用+运算符正常工作,那么是否隐式转换为测试类型对象?

class test {
double d;
int m;
public:
test()
{
    d=0;
    m=0;
}
test(double n)
{
    d=n;
}
const test operator+(const test& t)
{
    test temp;
    temp.d = d+ t.d;
    return temp;
}
};

int main()
{
   test t1(1.2);
   test t2(2.5);
   test t3, t4;
   t3= t1+ t2;
   t4 = t3 + 1.0;
   return 0;
 }

2 个答案:

答案 0 :(得分:0)

构造函数test(double n)声明从doubletest的隐式转换。通常,任何可以使用一个参数(包含可以接受更多参数但具有默认值的构造函数)可调用的构造函数都可以用作隐式转换,除非它被标记为explicit:< / p>

struct Foo {
    Foo(int x); // implicit conversion from int to Foo
    explicit Foo(char c); // marked explicit - no implicit conversion
    Foo(std::string a, double pi = 3.14159); // can be used as implicit 
                                             // conversion due to default 
                                             // argument
};

编辑: t4 = 1.0 + t3不起作用,因为您已将operator+重载为成员函数,因此仅考虑第一个操作数是否为类型test - 在这种情况下不尝试隐式转换。为了使这项工作,让您的操作员成为一个自由的功能:

test operator+(const test& lhs, const test& rhs);

答案 1 :(得分:0)

是的,只要您的构造函数test(double)不明确

// implicite convertible
test(double n)
{
  d=n;
}

// not implicite convertible
explicit test(double n)
{
  d=n;
}
相关问题