如果我们在任何函数中执行这两行,我们都会得到一个错误,这是合乎逻辑的,因为变量b是在初始化之后定义的a = b:
int a = b;
int b = 0;
Run Code Online (Sandbox Code Playgroud)
但是当我们将这两行插入到类的作用域中时,为什么类不关心定义的顺序呢b?
class Foo
{
int a = b;
int b = 0;
};
Run Code Online (Sandbox Code Playgroud) =运算符时,编译器如何知道使用构造函数?#include <string>
class Person
{
public:
std::string name;
Person(const char* fullName) : name(fullName) {}
};
int main()
{
Person p1("Jibel Sadeghi"); // This is ok because we declared the constructor with a const char*
/* When we didn't overload the '=' operator for 'const char*',
how the next lines don't have any errors? */
p1 = "Ben Sadeghi";
}
Run Code Online (Sandbox Code Playgroud) c++ oop constructor operator-overloading assignment-operator