我正在学习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
你的C++教科书对这个主题有什么要说的? –
初始化与赋值不同。 – user0042