C++第4讲:构造和析构

    科技2025-09-11  68

    #include<iostream> #include<cmath> using namespace std; class Test { public: //test类的构造函数 //在对象呗创建的时候,用来初始化对象的函数 Test(int x, int y) { m_x = x; m_y = y; } //构造函数是可以被重载的 Test(int x) { m_x = x; m_y = 0; } //无参构造构造函数,默认初始值为0 Test() { m_x = 0; m_y = 0; } //析构函数 //析构函数和构造函数都没有返回值 //析构函数没有形参 ~Test() { cout << "~test..." << endl; } void printT() { cout << "x = " << m_x << " y = " << m_y << endl; } private: int m_x; int m_y; }; void test1() { Test t3(100, 300); t3.printT(); } int main(void) { Test t1(10, 20); t1.printT(); cout << "-------------" << endl; Test t2(100); t2.printT(); cout << "-------------" << endl; Test t3;//这个调用的时候,什 么都不写就可以直接调用无参构造函数了 t3.printT(); test1(); system("pause"); return 0; }

    (完!)

    Processed: 0.010, SQL: 8