主要是熟悉构造函数的使用。
第一个代码是在类外定义构造函数。
#include<iostream>
using namespace std;
class Desk{
private:
double length;
double width;
double high=3;
double weight=2.2;
public:
Desk(double,double);
void display(){
cout<<"weight="<<weight<<"\thigh="<<high<<endl;
cout<<"length="<<length<<"\twidth="<<width<<endl;
}
};
Desk::Desk(double l,double w){
length=l;
width=w;
}
int main(){
Desk a(4.2,5.5);
a.display();
}
接下来是在类内定义构造函数:
#include<iostream>
using namespace std;
class Desk{
private:
double length;
double width;
double high=3;
double weight=2.2;
public:
Desk(double l,double w){
length=l;
width=w;
}
void display(){
cout<<"weight="<<weight<<"\thigh="<<high<<endl;
cout<<"length="<<length<<"\twidth="<<width<<endl;
}
};
int main(){
Desk a(4.2,5.5);
a.display();
}
值得一提的是,构造函数并不需要写void,这点需要和其它的类函数区别一下。