#i nclude <iostream>
class A
{
public:
A(int value):
_value(value)
{
}
void showValue() const
{
std::cout << "A._value = " << _value << std::endl ;
}
private:
int _value ;
};
class B
{
public:
explicit B(int value):
_value(value)
{
}
void showValue() const
{
std::cout << "B._value = " << _value << std::endl ;
}
private:
int _value ;
};
class C
{
public:
void testA(const A& a)
{
a.showValue() ;
}
void testB(const B& b)
{
b.showValue() ;
}
};
int main()
{
C test ;
A a = 2000 ; // OK, 相当于 A a = A(2000) ; 隐式调用了构造函数 A(int value)
test.testA(a) ;
test.testA(1000) ; //OK 隐式构造了一个 A(1000) 的临时对象,然后调用函数C.testA(const A& a)
//B b1 = 2000 ; //can't pass compile, 因为explicit 关键字禁止隐式构造对象。
B b = B(2000) ; // 如果有explicit关键字,必须显式调用构造
test.testB(b) ; //OK
//test.testB(1000) ;//can't pass compile, 因为explicit 关键字禁止隐式构造对象。
return 0 ;
}
C++ 中的 explicit 关键字
最新推荐文章于 2025-04-09 14:14:56 发布