构造函数

2019-07-16  本文已影响0人  始于尘埃
#include <iostream>
#include <string>
using namespace std;

class Car{
    //为了调用方便,我把数据改成公有
    public:
        string name;
        int cost;
        string color;
    public:
        //定初始化列表(用户自定义参数)
        Car(string Name,int Cost,string Color):name(Name),cost(Cost),color(Color) {};
        //定义默认构造函数(当没有参数传入时,自动调用)
        Car();
};
Car::Car(){
    name = "Rice";
    cost = 1000;
    color = "Red";
}
int main(){
    Car car2;
    //调用初始化列表(自定义)
    Car car1("Moon",99999,"blue");
    //调用默认构造函数
    //car2();不能单独调用构造函数
    cout<<car1.name<<car1.color<<car1.cost<<"\n";
    cout<<car2.name<<car2.color<<car2.cost<<endl;
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读