1:在创建对象时,程序自动调用构造函数。同一个类中可以有多个构造函数,通过这样的形式创建一个CPerson对象,例如:

CPerson p1(0,"jack",22,7000);

CPerson p2=Cperson(1,"tony",25,8000);

CPerson p;

2:利用构造函数初始化成员变量的代码如下:

 (1)person.h中

#include <string>//本题目的目的是利用构造函数初始化成员变量
using std::string;
class CPerson
{
public:
    //构造函数
     CPerson(int index,string name,short age,double salary);//构造函数是对数据成员来说的,所以参数和下面的数据成员一样
    CPerson();
    //数据成员
    int m_iIndex;
    string m_sName;
    short m_shAge;
    double m_dSalary;
    //成员函数
    short getAge();
    int setAge(short sAge);
    int getIndex() ;
    int setIndex(int iIndex);
    string getName() ;
    int setName(string sName);
    double getSalary() ;
    int setSalary(double dSalary);
};
View Code

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-02-13
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2021-09-11
  • 2021-09-12
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
相关资源
相似解决方案