C++有参构造函数的几种方式

  • Post author:
  • Post category:其他




c++中调用无参数构造函数

#include <iostream>
using namespace std;
 
class A {
public:
	//无参构造函数
	A() {
		cout << "调用无参构造函数" << endl;
	}
	~A() {
		cout << "调用析构函数" << endl;
	}
};
void obj() {
	//定义类A的对象,并调用无参构造函数
	A a;
}
 
int main()
{
	obj();
    cout << "Hello World!\n";
	system("pause");
}



c++中,调用有参数构造函数有三种方式:

#include<iostream>
using namespace std;
class Test {
private:
	int a;
	int b;
public:
	//定义带参数的构造函数
	Test(int a) {
		cout << "a  = " << a <<endl;
	}
	Test(int a, int b) {
		cout << "a = " << a << "  b = " << b << endl;
	}
 
};
int main() {
	// 1、 括号法
	Test t1(10);
	Test t2(10, 20);
	// 2. 等号法
	Test t3 = (1, 2,3);
	// 3. 构造函数法, 手动直接调用构造函数
	Test t4 = Test(10, 20);
	system("pause");
}

在这里插入图片描述

本文转载链接:https://blog.csdn.net/qq_20880939/article/details/103064425