我不明白以下几点。如果我有:
class Stack{
explicit Stack(int size);
}
没有关键字explicit
我将被允许这样做:
Stack s;
s = 40;
如果没有提供显式,为什么我会被允许这样做?是因为这是堆栈分配(没有构造函数),C ++允许将任何内容分配给变量,除非使用explicit
吗?
答案 0 :(得分:6)
这一行
s = 40;
相当于
s.operator = (40);
尝试匹配默认operator = (const Stack &)
。如果Stack
构造函数不明确,则尝试以下转换并成功:
s.operator = (Stack(40));
如果构造函数为explicit
,则不会尝试进行此转换,并且重载决策失败。
答案 1 :(得分:1)
#include iostream
using namespace std;
class A
{
private:
int x;
public:
A(int a):x(a)
{}
}
int main()
{
A b=10; // this syntax can work and it will automatically add this 10 inside the
// constructor
return 0;
}
but here
class A
{
private:
int x;
public:
explicit A(int a):x(a)
{}
}
int main()
{
A b=10; // this syntax will not work here and a syntax error
return 0;
}