C++入门经典-例7.2-利用构造函数初始化成员变量

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

(2)person.cpp中

#include "stdafx.h"
#include <iostream>
#include "person.h"
//类成员函数的实现部分
short CPerson::getAge() 
{ 
    return m_shAge; 
}
int CPerson::setAge(short sAge)
{
    m_shAge=sAge;
    return 0;                                //执行成功返回0
}
int CPerson::getIndex() 
{ 
    return m_iIndex; 
}
int CPerson::setIndex(int iIndex)
{
    m_iIndex=iIndex;
    return 0;                                //执行成功返回0
}
string CPerson::getName() 
{ 
    return m_sName; 
}
int CPerson::setName(string sName)
{
    m_sName = sName;
    return 0;                                //执行成功返回0
}
double CPerson::getSalary() 
{ 
    return m_dSalary; 
}
int CPerson::setSalary(double dSalary)
{
    m_dSalary=dSalary;
    return 0;                                //执行成功返回0
}
  CPerson::CPerson(int index,string name,short age,double salary)
  {
      m_iIndex = index;
      m_sName = name;
      m_shAge = age;
      m_dSalary = salary;
  }
    CPerson::CPerson()
    {

    }
View Code

(3)main.cpp中

// 7.2.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include "Person.h"
using std::cout;
using std::endl;
void main()
{
    string str("tony");//注意string的用法
    CPerson p1;
    CPerson p2 = CPerson(1, str,25,8000);
    cout<<"p1的信息:"<<endl;
    cout << "m_shAge is:" << p1.getAge() << endl;
    cout << "m_iIndex is:" << p1.getIndex() << endl;
    cout << "m_cName is:" << p1.getName() << endl;
    cout << "m_dSalary is:" << p1.getSalary() << endl;
    cout<<"p2的信息:"<<endl;
    cout << "m_shAge is:" << p2.getAge() << endl;
    cout << "m_iIndex is:" << p2.getIndex() << endl;
    cout << "m_cName is:" << p2.getName() << endl;
    cout << "m_dSalary is:" << p2.getSalary() << endl;
}
View Code

运行结果:

原文地址:https://www.cnblogs.com/lovemi93/p/7545379.html