1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| #include <iostream> class Person { private: int m_Age; public: Person() { std::cout << "无参构造/默认构造函数" << std::endl; } ~Person() { std::cout << "析构函数" << std::endl; } Person(int a) { std::cout << "有参构造函数" << std::endl; m_Age = a; } Person(const Person& other) { std::cout << "拷贝构造函数" << std::endl; m_Age = other.m_Age; } };
int main() { Person p1(); Person p2(18); Person p3(other); Person p1 = Person(); Person p2 = Person(18); Person p3 = Person(other); Person p1; Person p2 = 18; Person p3 = other; ----------------------------------------------------------------------------- Person(); Person(18); Person(p2); 而 C++ 语法规则规定:
当一条语句“既可以被解析为声明,又可以被解析为表达式”时,必须优先解析为声明。 ----------------------------------------------------------------------------- Person p1(); Person p2 = Person(); Person p3; Person p1(18); Person p2 = Person(18); Person p3 = 18; Person p1(other); Person p2 = Person(other); Person p3 = other; }
|