#include<iostream>usingnamespace std;classLine{public:voidsetLength(double len );doublegetLength(void);Line();// 这是构造函数private:double length;};// 成员函数定义,包括构造函数Line::Line(void){
cout <<"Object is being created"<< endl;}voidLine::setLength(double len ){
length = len;}doubleLine::getLength(void){return length;}// 程序的主函数intmain(){
Line line;// 设置长度
line.setLength(6.0);
cout <<"Length of line : "<< line.getLength()<<endl;
Line line1;return0;}
拷贝构造函数
#include<iostream>usingnamespace std;classLine{public:intgetLength(void);Line(int len );// 简单的构造函数Line(const Line &obj);// 拷贝构造函数~Line();// 析构函数private:int*ptr;};// 成员函数定义,包括构造函数Line::Line(int len){
cout <<"调用构造函数"<< endl;// 为指针分配内存
ptr =newint;*ptr = len;}Line::Line(const Line &obj){
cout <<"调用拷贝构造函数并为指针 ptr 分配内存"<< endl;
ptr =newint;*ptr =*obj.ptr;// 拷贝值}Line::~Line(void){
cout <<"释放内存"<< endl;delete ptr;}intLine::getLength(void){return*ptr;}voiddisplay(Line obj){
cout <<"line 大小 : "<< obj.getLength()<<endl;}voidfun(){
cout<<"not use Line"<<endl;}// 程序的主函数intmain(){
Line line1(10);
Line line2 = line1;// 这里也调用了拷贝构造函数
cout<<endl<<"dispaly_line1"<<endl;display(line1);
cout<<endl<<"dispaly_line2"<<endl;display(line2);
cout<<"over"<<endl;fun();return0;}
#include<iostream>usingnamespace std;classLine{public:voidsetLength(double len );doublegetLength(void);Line();// 这是构造函数声明~Line();// 这是析构函数声明private:double length;};// 成员函数定义,包括构造函数Line::Line(void){
cout <<"Object is being created"<< endl;}Line::~Line(void){
cout <<"Object is being deleted"<< endl;}voidLine::setLength(double len ){
length = len;}doubleLine::getLength(void){return length;}// 程序的主函数intmain(){
Line line;// 设置长度
line.setLength(6.0);
cout <<"Length of line : "<< line.getLength()<<endl;
line.setLength(7.0);
cout <<"Length of line : "<< line.getLength()<<endl;return0;}