C ++:为什么构造器“A(A a){}”是非法的? [英] C++: why constructor "A(A a) {}" is illegal?
问题描述
我遇到了一个测验,说下面的代码是错误的,因为有一个构造函数,其第一个也是唯一的非默认参数是类类型的值参数是非法的。
我不明白。为什么 A(A a):val(a.val){}
被判定为非法?为什么这样的线在标准?是因为这会导致复制构造函数的模糊性吗?
#include< iostream>
struct A
{
A():val(){}
A(int v):val(v){}
A A a):val(a.val){}
int val;
}
int main(int argc,char ** argv)
{
A a1(5);
A a2(a1);
std :: cout<< a1.val + a2.val< std :: endl;
return 0;
}
A(A a):val(a.val){}
将导致无限递归,因为构造函数参数被值复制(调用复制构造函数和复制构造函数...) p>
I met a quiz saying that the code below is ill-formed because "It is illegal to have a constructor whose first and only non-default argument is a value parameter for the class type."
I couldn't understand that. Why things like A(A a) : val (a.val) {}
is ruled as illegal? why such a line in the standard? Is it because this will lead to ambiguity with copy constructor?
#include <iostream>
struct A
{
A() : val() {}
A(int v) : val(v) {}
A(A a) : val(a.val) {}
int val;
};
int main(int argc, char** argv)
{
A a1(5);
A a2(a1);
std::cout << a1.val + a2.val << std::endl;
return 0;
}
A(A a) : val(a.val) {}
will cause an infinite recursion because constructor arguments are being copied by value (invoking copy constructor and again the copy constructor and ...)
这篇关于C ++:为什么构造器“A(A a){}”是非法的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!