我有一个关于 C++ 语法/构造的查询:在什么情况下可以调用以下 Foo(Foo x){}? 我知道它不会像初始化一样被调用,因为它们会调用复制构造函数
Foo a;
Foo x = a;
or
Foo x(a);
不用于类型转换,因为传递给它的参数与类的类型相同
想不出调用 Foo(Foo x){} 的场景,否则它永远是死代码。
class Foo {
public :
Foo(Foo x){ // notice it is not not a Copy constructor!!, i intented it to make like ordinary ctor taking same class object
}
Foo(int x) : m_data(x){}
private :
int m_data;
};
最佳答案
你真的试过编译这段代码吗?
Error 1 error C2652: 'Foo' : illegal copy constructor: first parameter must not be a 'Foo' main.cpp 5 1 NativeConsoleSketchbook
C++11 标准,12.8.6:
A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments.
关于c++ - Foo(Foo x){ } 会在 C++ 中被调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780420/