如果在创建对象的时候,没有传递实参给该参数p,则该参数会被默认设置为5.0。book(char* a, double p = 5.0);
#include<iostream>using namespace std;class book{public:book(){}book(char* a, double p = 5.0);//默认参数5void display();private:double price;char * title;};book::book(char* a, double p) //在定义函数的时候可以不指定默认参数{title = a;price = p;}void book::display(){cout<<"The price of "<<title<<" is $"<<price<<endl;}int main(){book Harry("Harry Potter", 49.9);Harry.display();book Gone("Gone with the Wind");Gone.display();return 0;}
默认带参构造函数所带来的歧义:
#include<iostream>using namespace std;class book{public:book(){}book(char* a, double p = 5.0);book(char *a);void setprice(double a);double getprice();void settitle(char* a);char * gettitle();void display();private:double price;char * title;};book::book(char* a, double p) //在定义函数的时候可以不指定默认参数{title = a;price = p;}book::book(char *a){title = a;}void book::display(){cout<<"The price of "<<title<<" is $"<<price<<endl;}int main(){book Harry("Harry potter", 49.9);Harry.display();book Gone("Gone with the Wind"); //compile errorGone.display();return 0;}
出现这种情况我们只能极力去避免了,通常而言,在设计类的构造函数的时候最好不要同时是用构造函数的重载和带参数的构造函数,以避免上述问题。