我正在学习C ++并在学习构造函数的使用时遇到这个问题。请考虑以下代码段:
#include <string>
#include <iostream>
using namespace std;
class Foo
{
public:
Foo() { m_ = 0; cout << "default ctor called." << endl; }
Foo(int a) { m_ = 1; cout << "int ctor called." << endl; }
Foo(string str) { m_ = 2; cout << "str ctor called." << endl; }
Foo(Foo& f)
{
cout << "copy ctor called." << endl;
m_ = f.m_;
}
Foo& operator=(string str)
{
cout << "= operator called." << endl;
m_ = 3;
return *this;
}
int m_;
};
int main()
{
Foo f1 = 100;
cout << f1.m_ << endl;
Foo f2 = "ya";
cout << f2.m_ << endl;
Foo f3("ha");
cout << f3.m_ << endl;
f1 = "hee";
cout << f1.m_ << endl;
Foo f4 = Foo();
cout << f4.m_ << endl;
return 0;
}
我意识到了
Foo f1 = 100;
Foo f2 = "ya";
实际上调用构造函数就好像我在做
Foo f1(100);
Foo f2("ya");
我没有找到任何相关的解释。谁能请解释这里发生了什么? 以下主题与我的关系很接近,但并没有完全回答我的问题。 C++ Object Instantiation vs Assignment
答案 0 :(得分:2)
Foo
对象是根据分配给对象(implicit conversation)
只要某种类型的表达式执行隐式转换 T1用于不接受该类型的上下文中,但接受一些 其他类型T2
在此上下文中使用它。然后copy-initializtion从另一个对象初始化一个对象(通过前面提到的隐式对话构建)
您可以使用explicit
关键字将其停用(仅适用于此构造函数)。
explicit Foo(int a)
进行此操作
Foo f1 = 100;
非法的。