2012年(1008)
分类:
2012-08-01 11:10:40
原文地址:构造函数实例 作者:luozhiyong131
/*
* 无参构造函数举例
* Lzy 2011-8-2
*/
#include
using namespace std;
class Data
{
private:
int year, month, date;
public:
Data();
void GetData();
};
Data::Data()
{
year = 2011; month = 8; date = 2;
}
void Data::GetData()
{
cout<
}
int main(void)
{
Data data;
data.GetData();
}
/*
* 带参参构造函数举例
* Lzy 2011-8-2
*/
#include
using namespace std;
class Data
{
private:
int year, month, date;
public:
Data();
Data(int y, int m, int d);
void GetData();
};
Data::Data()
{
year = 2011; month = 8; date = 2;
}
Data::Data(int y, int m, int d)
{
year = y; month = m; date = d;
}
void Data::GetData()
{
cout<
}
int main(void)
{
Data data, data1(2012,12,23);
data.GetData();
data1.GetData();
}
/*
* 带默认值参参的初始化式构造函数举例
* Lzy 2011-8-2
*/
#include
using namespace std;
class Data
{
private:
int year, month, date;
public:
Data(int y=2011, int m=8, int d=2):year(y),month(m),date(d){}
void GetData();
};
void Data::GetData()
{
cout<
}
int main(void)
{
Data data, data1(2012,12,23);
data.GetData();
data1.GetData();
}
/*
* 类嵌套、对像成员初始化实例
* Lzy 2011-8-2
*/
#include
using namespace std;
class ClassA
{
public:
int x;
ClassA(int X)
{
cout<<"In ClassA"<
x = X;
}
};
class ClassB
{
private:
ClassA a;
int b;
public:
ClassB();
ClassB(int x, int y);
void pritn(void);
};
ClassB::ClassB():a(99)
{
cout<<"In ClassB"<
b = 99;
}
ClassB::ClassB(int x, int y):a(x),b(y)
{
cout<<"In ClassB"<
}
void ClassB::pritn(void)
{
cout<<"a="<
}
int main(void)
{
ClassB b1, b2(10,10);
b1.pritn();
b2.pritn();
return 0;
}
/*
* this指针的使用
* Lzy 2011-8-2
*/
#include
using namespace std;
class Person
{
private:
int age;
public:
Person():age(20){}
void display(void);
};
void Person::display(void)
{
cout<<this->age<
}
int main(void)
{
Person lzy;
lzy.display();
}