带赋值运算符的构造函数 我学习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; }

带赋值运算符的构造函数 我学习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; },c++,constructor,C++,Constructor,实际上调用构造函数,就好像我在做 Foo f1(100); Foo f2("ya"); 我找不到任何相关的解释。谁能解释一下这里发生了什么事? 下面的主题与我的主题很接近,但没有完全回答我的问题。 对象是根据分配给对象()的值构造的 每当某个类型的表达式出现时,都会执行隐式转换 T1用于不接受该类型但接受某些类型的上下文中 其他类型T2 在此上下文中使用它的位置。然后从另一个对象初始化一个对象(通过前面提到的隐式对话构造) 您可以使用explicit关键字禁用它(仅用于此构造函数) expl

实际上调用构造函数,就好像我在做

Foo f1(100);

Foo f2("ya");
我找不到任何相关的解释。谁能解释一下这里发生了什么事? 下面的主题与我的主题很接近,但没有完全回答我的问题。
对象是根据分配给对象()的值构造的

每当某个类型的表达式出现时,都会执行隐式转换 T1用于不接受该类型但接受某些类型的上下文中 其他类型T2

在此上下文中使用它的位置。然后从另一个对象初始化一个对象(通过前面提到的隐式对话构造)

您可以使用
explicit
关键字禁用它(仅用于此构造函数

explicit Foo(int a)
这使得这个手术

Foo f1 = 100;

< C++ >教科书中有什么要对这个主题说的?初始化不同于赋值。这不会禁用复制初始化。它禁用从
int
Foo
的转换。它不直接禁用复制初始化。只是复制初始化不考虑显式构造函数。禁用复制初始化将不允许
Foo f;Foo g=f,你的代码没有。好吧,你现在已经完全重写了你的答案,所以这些评论是没有意义的。我显然混淆了赋值和初始化的概念。在使用了正确的关键字之后,我可以找到更多的资源。非常感谢你。
Foo f1 = 100;