C++使用默认参数的构造函数

#include<iostream>
using namespace std;

class book
{
public:
    book(){cout<<"first"<<"\n"<<endl;}
    book(char* a, double p = 5.0);
    void display();
private:
    double price;
    char * title;
};

book::book(char* a, double p)  //在定义函数的时候可以不指定默认参数
{
    cout<<"second"<<"\n"<<endl;
    title = a;
    price = p;
}

void book::display()
{
    cout<<"The price of "<<title<<" is $"<<price<<endl;
}

int main()
{

    book Three_kiongdom;
    book Harry("Harry Potter", 49.9);
    Harry.display();
    book Gone("Gone with the Wind");
    Gone.display();
    return 0;
}
first

second

The price of Harry Potter is $49.9
second

The price of Gone with the Wind is $5

Process finished with exit code 0
posted @ 2022-08-19 22:48  luoganttcc  阅读(5)  评论(0)    收藏  举报