构造函数使用代码:
#include <iostream>
using namespace std;
class Rec
{
const int length;
int width;
public:
Rec():length(10){cout << "Rec无参构造函数" << endl;};
Rec(int a,int b):length(a),width(b){cout << "Rec有参构造函数" << endl;};
void set_length(int l);
void set_width(int w);
int get_length();
int get_width();
void show();
};
class Cir
{
int &r;
public:
Cir(int &a):r(a){cout << "Cir有参构造函数" << endl;};
void set_r(int r); //设置私有属性r的值
void show(double PI=3.14); //参数有默认值3.14
};
class Car //类名首字母一般大小
{
string color;
string brand;
int speed;
public:
Car(){cout << "Car无参构造函数" << endl;};
Car(string a,string b,int c):color(a),brand(b),speed(c){cout << "Car有参构造函数" << endl;};
void set(string c,string b,int s);
void display();
void acc(int a);
};
int main()
{
Rec a;
int age=100;
Rec b(age,22.2);
int cc=8;
Cir c(cc);
Car s;
Car ss("黑曜金","迈巴赫",200);
Car *p=new Car[4];
}
Xmind知识点: