gpt4 book ai didi

c++ - static_cast 转换构造函数 vs 转换运算符

转载 作者:可可西里 更新时间:2023-11-01 18:29:12 24 4
gpt4 key购买 nike

<分区>

看完this我尝试使用 static_cast 进行此类转换:

class A;

class B {
public:
B(){}

B(const A&) //conversion constructor
{
cout << "called B's conversion constructor" << endl;
}
};

class A {
public:
operator B() const //conversion operator
{
cout << "called A's conversion operator" << endl;
return B();
}
};

int main()
{
A a;

//Original code, This is ambiguous,
//because both operator and constructor have same cv qualification (use -pedantic flag)
B b = a;

//Why isn't this ambiguous, Why is conversion constructor called,
//if both constructor and operator have same c-v qualification
B c = static_cast<B>(a);
return 0;
}

我预计它不会编译,因为构造函数和运算符都具有相同的 c-v 资格。然而,它编译成功,static_cast 调用构造函数而不是运算符。为什么?

(使用带有 pedanticWall 标志的 gcc 4.8.1 编译)

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com