#include <iostream>
using namespace std;
class A {
public:
protected:
private:
};
struct C {
};
class B {
public:
protected:
private:
A a;
int a2;
};
void main() {
printf("A:%d \n", sizeof(A));
printf("C:%d \n", sizeof(C));
system("pause");
}
class Test {
public:
Test() { // 无参构造函数
p = (char*)malloc(100);
if (p != NULL) strcpy_s(p, "11111");
cout << "我是构造函数,自动被调用了" << endl;
}
Test(int _a = 0, int _b = 0) { // 有参构造函数
p = (char*)malloc(100);
strcpy_s(p, "11111");
a = _a;
b = _b;
cout << "我是有参构造函数,自动被调用了" << endl;
}
~Test() {
cout << "我是析构函数,自动被调用了" << endl;
if (p != NULL) {
cout << "free(p)" << endl;
free(p);
}
}
protected:
private:
int a;
int b;
char* p;
};
void test() {
// 有参构造方法3种调用方法
// 1 ()括号法
Test t1(1, 2);
// 2 = 等号赋值法
Test t2 = (1, 2);
// 3 手动法
Test t3 = Test(3, 4);
cout << "展示t1生命周期" << endl;
}
int main01()
{
test();
system("pause");
}
C++有参构造函数的调用方法
最新推荐文章于 2023-09-12 03:45:00 发布