#include<iostream>
using namespace std;
//不带参数的构造函数
class Data
{
public:
void SetNum(int x);
int GetNum();
Data();//构造函数
private:
int mynum;
};
//成员函数定义,包括构造函数
Data::Data()
{
cout << "Object is being created" << endl;
}
void Data::SetNum(int x)
{
mynum = x;
}
int Data::GetNum()
{
return mynum;
}
int main()
{
Data data1;
data1.SetNum(5);
cout << "NUM IS : " << data1.GetNum() << endl;
return 0;
}
输出结果
//带参数的构造函数
#include<iostream>
using namespace std;
class Data
{
public:
void SetNum(int x);
int GetNum();
Data(int x);//带参数的构造函数
private:
int mynum;
};
// 成员函数定义,包括构造函数
Data::Data(int x)
{
cout << "Object is being created" << endl;
mynum = x;
}
void Data::SetNum(int x)
{
mynum = x;
}
int Data::GetNum()
{
return mynum;
}
int main()
{
Data data(20);//构造函数
// 获取默认设置数据
cout << "NUM IS : " << data.GetNum() << endl;
// 再次设置数据
data.SetNum(5);
cout << "NUM IS : " << data.GetNum() << endl;
return 0;
}
输出结果
20是构造函数默认的,5是重新设置获取的
3.构造与析构
#include<iostream>
using namespace std;
class Data
{
public:
void SetNum(int x);
int GetNum();
Data(int x);//带参数的构造函数
~Data();//这是析构函数
private:
int mynum;
};
// 成员函数定义,包括构造函数
Data::Data(int x)
{
cout << "对象初始化:构造函数" << endl;
mynum = x;
}
Data::~Data()
{
cout << "对象清理:析构函数" << endl;
}
void Data::SetNum(int x)
{
mynum = x;
}
int Data::GetNum()
{
return mynum;
}
int main()
{
Data data(20);//构造函数
// 获取默认设置数据
cout << "NUM IS : " << data.GetNum() << endl;
// 再次设置数据
data.SetNum(5);
cout << "NUM IS : " << data.GetNum() << endl;
return 0;
}
输出结果: