1. 程式人生 > >建構函式使用預設引數後不能使用建構函式過載

建構函式使用預設引數後不能使用建構函式過載

#include<iostream>
class Date
{
	public:
		Date(int,int,int);
		Date(int,int);
		Date(int); 
		Date();
		void display();
		private:
			int month;
			int day;
			int year;
};
Date::Date(int m,int d,int y):month(m),day(d),year(y){
}
Date::Date(int m,int d):month(m),day(d){
	year=2005;
}
Date::Date(int m):month(m)
{
	day=1;
	year=2005;
}
Date::Date()
{
	month=1;
	day=1;
	year=2005;
} 
void Date::display()
{
	std::cout<<month<<"/"<<day<<"/"<<year<<std::endl;

}
int main()
{
	Date d1(10,13,2005);
	Date d2(12,30);
	Date d3(10);
	Date d4;
	d1.display();
	d2.display();
	d3.display();
	d4.display(); 
	return 0;
}

結果:


Date(int,int,int);改為<pre name="code" class="cpp">Date(int=1,int=1,int=2005);

#include<iostream>
class Date
{
	public:
		Date(int=1,int=1,int=2005);
		Date(int,int);
		Date(int); 
		Date();
		void display();
		private:
			int month;
			int day;
			int year;
};
Date::Date(int m,int d,int y):month(m),day(d),year(y){
}
Date::Date(int m,int d):month(m),day(d){
	year=2005;
}
Date::Date(int m):month(m)
{
	day=1;
	year=2005;
}
Date::Date()
{
	month=1;
	day=1;
	year=2005;
} 
void Date::display()
{
	std::cout<<month<<"/"<<day<<"/"<<year<<std::endl;

}
int main()
{
	Date d1(10,13,2005);
	Date d2(12,30);
	Date d3(10);
	Date d4;
	d1.display();
	d2.display();
	d3.display();
	d4.display(); 
	return 0;
}
編譯:

[Error] call of overloaded 'Date(int, int)' is ambiguous

#include<iostream>
class Date
{
	public:
		Date(int=1,int=1,int=2005);
		void display();
		private:
			int month;
			int day;
			int year;
};
Date::Date(int m,int d,int y):month(m),day(d),year(y){
}

void Date::display()
{
	std::cout<<month<<"/"<<day<<"/"<<year<<std::endl;

}
int main()
{
	Date d1(10,13,2005);
	Date d2(12,30);
	Date d3(10);
	Date d4;
	d1.display();
	d2.display();
	d3.display();
	d4.display(); 
	return 0;
}