1.使用构造函数进行初始化操作
#include <iostream>
using namespace std;
class CPerson
{
public:
CPerson();
CPerson(int ilndex, short m_shAge, double m_dSalary);
int m_ilndex;
short m_shAge;
double m_dSalary;
int getlndex();
short getAge();
double getSalary();
};
//在默认构造函数中初始化
CPerson::CPerson()
{
m_ilndex = 0;
m_shAge=10;
m_dSalary=1000;
}
//在带参数的构造函数中初始化
CPerson::CPerson(int ilndex, short m_shAge, double m_dSalary)
{
m_ilndex = ilndex;
m_shAge = m_shAge;
m_dSalary = m_dSalary;
}
int CPerson::getlndex()
{
return m_ilndex;
}
//在main函数中输出类的成员值
void main()
{
CPerson p1;
cout << "m_ilndex is:" << p1.getlndex() << endl;
CPerson p2(1,20,1000);
cout << "m_ilndex is:" << p2.getlndex() << endl;
system("pause");
}
结果:
2.Person.h Person.cpp main.cpp
a.类的声明person.h
#pragma once
//#include <stdio.h>
//#include <stdlib.h>
//#include <string.h>
//定义CPerso类
class CPerson
{
public:
CPerson();
CPerson(int ilndex, short m_shAge, double m_dSalary);
int m_ilndex;
short m_shAge;
double m_dSalary;
int getlndex();
short getAge();
double getSalary();
};
b.类的执行person.cpp
#include <iostream>
#include "Person.h"
using namespace std;
//在默认构造函数中初始化
CPerson::CPerson()
{
m_ilndex = 0;
m_shAge = 10;
m_dSalary = 1000;
}
//在带参数的构造函数中初始化
CPerson::CPerson(int ilndex, short m_shAge, double m_dSalary)
{
m_ilndex = ilndex;
m_shAge = m_shAge;
m_dSalary = m_dSalary;
}
int CPerson::getlndex()
{
return m_ilndex;
}
c.main.cpp
#include <iostream>
#include "Person.h"
using namespace std;
//在main函数中输出类的成员值
void main()
{
CPerson p1;
cout << "m_ilndex is:" << p1.getlndex() << endl;
CPerson p2(1,20,1000);
cout << "m_ilndex is:" << p2.getlndex() << endl;
system("pause");
}
结果:
3.定义命名空间
#include <iostream>
using namespace std;
namespace MyName1 //定义命名空间
{
int iValue = 10;
};
namespace MyName2 //定义命名空间
{
int iValue = 20;
};
int iValue = 30; //全局变量
void main()
{
cout << MyName1::iValue << endl; //引用MyName1命名空间中的变量
cout << MyName2::iValue << endl; //引用MyName2命名空间中的变量
cout << iValue << endl;
system("pause");
}
结果:
4.使用using namespce语句
#include <iostream>
namespace MyName //定义命名空间
{
int iValue = 10;
};
using namespace std;
using namespace MyName;
void main()
{
cout << iValue << endl;
system("pause");
}
结果: