Default constructor and default parameter constructor

  • A constructor with default parameters is equivalent to a default constructor without parameters
  • In a constructor with multiple default parameters, the first parameter has a default value, and the compiler considers it to be a default constructor


#include <iostream>
using namespace std;
class A {
	public:
		A(){x=0;y=0;}
//If there is a default parameter on the leftmost side, the constructor is considered to be a default constructor, for example: A(int a=0,int b) or A(int a=0,int b=0);
//Conversely, it is not a default constructor, such as A(int a,int b=0) A(int a,int b=0, int c=0)
		A(int a,int b) { //Constructor without default parameter values
			x=a;
			y=b;
		}
		A (A& obj) { //copy constructor
			x=obj.x;
			y=obj.y;
			cout<<"copy_constructor called."<<endl;
		}

		int Getx() {
			return x;
		}
		int Gety () {
			return y;
		}
	private:
		int x,y;
};

void fun(A a) {
	cout<<a.Getx()<<","<<a.Gety()<<endl;
}
int main() {
	A a2;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326359937&siteId=291194637
Recommended