一、建立一個類,C++編譯器會給每一個類都添加至少3個函數
(1)默認構造 (空實現)
(2)析構函數(空實現)
(3)拷貝構逍(值拷貝)ios
#include<iostream> #include<string> using namespace std; //構造函數的調用規則 //一、建立一個類,C++編譯器會給每一個類都添加至少3個函數 //默認構造 (空實現) //析構函數(空實現) //拷貝構逍(值拷貝) class Person { public: //普通構造函數 Person() { cout << "Person 無參構造函數的調用" << endl; } Person(int age) { m_age = age; cout << "Person 有參構造函數的調用" << endl; } //拷貝構造函數 /*Person(const Person &p) { m_age = p.m_age; cout << "Person 拷貝構造函數的調用" << endl; }*/ //析構函數 ~Person() { cout << "Person 析構函數的調用" << endl; } int m_age; }; void test01() { Person p1; p1.m_age = 18; //編譯器提供的拷貝構造函數 值拷貝 Person p2(p1); //p2.m_age = 18; cout << "p2的年齡爲:" << p2.m_age << endl; } int main(){ test01(); cout << "***********test01************" << endl; system("pause"); return 0; }
2.1 若是咱們寫了有參構造函數,編譯器就再也不提供默認構造,依然提供拷貝構造函數ide
#include<iostream> #include<string> using namespace std; //構造函數的調用規則 //一、建立一個類,C++編譯器會給每一個類都添加至少3個函數 //默認構造 (空實現) //析構函數(空實現) //拷貝構逍(值拷貝) //二、若是咱們寫了有參構造函數,編譯器就再也不提供默認構造,依然提供拷貝構造 class Person { public: //普通構造函數 /*Person() { cout << "Person 無參構造函數的調用" << endl; }*/ Person(int age) { m_age = age; cout << "Person 有參構造函數的調用" << endl; } //拷貝構造函數 /*Person(const Person &p) { m_age = p.m_age; cout << "Person 拷貝構造函數的調用" << endl; }*/ //析構函數 ~Person() { cout << "Person 析構函數的調用" << endl; } int m_age; }; void test02() { // Error:類"Person」不存在默認構造函數 //Person p3; } int main(){ test02(); cout << "***********test02************" << endl; system("pause"); return 0; }
#include<iostream> #include<string> using namespace std; //構造函數的調用規則 //一、建立一個類,C++編譯器會給每一個類都添加至少3個函數 //默認構造 (空實現) //析構函數(空實現) //拷貝構逍(值拷貝) //2.1 若是咱們寫了有參構造函數,編譯器就再也不提供默認構造,依然提供拷貝構造 //2.2 若是咱們寫了拷貝構造函數,編譯器就再也不提供其餘普通構造函數了 class Person { public: Person(int age) { m_age = age; cout << "Person 有參構造函數的調用" << endl; } //析構函數 ~Person() { cout << "Person 析構函數的調用" << endl; } int m_age; }; void test02() { // Error:類"Person」不存在默認構造函數 //Person p3; Person p4(28); Person p5(p4); cout << "p5的年齡爲:" << p5.m_age << endl; } int main(){ test02(); cout << "***********test02************" << endl; system("pause"); return 0; }
2.2 若是咱們寫了拷貝構造函數,編譯器就再也不提供其餘普通構造函數了函數
#include<iostream> #include<string> using namespace std; //構造函數的調用規則 //一、建立一個類,C++編譯器會給每一個類都添加至少3個函數 //默認構造 (空實現) //析構函數(空實現) //拷貝構逍(值拷貝) //2.1 若是咱們寫了有參構造函數,編譯器就再也不提供默認構造,依然提供拷貝構造 //2.2 若是咱們寫了拷貝構造函數,編譯器就再也不提供其餘普通構造函數了 class Person { public: //拷貝構造函數 Person(const Person &p) { m_age = p.m_age; cout << "Person 拷貝構造函數的調用" << endl; } //析構函數 ~Person() { cout << "Person 析構函數的調用" << endl; } int m_age; }; void test02() { //Error:類"Person」不存在默認構造函數 //Person p; } int main(){ test02(); cout << "***********test02************" << endl; system("pause"); return 0; }