条款23宁以non-member函数代替member函数 (二)
dperson
{
void PrintMessage(Person p);
}
#endif
4 onemethod.cpp
[cpp]
#include "onemethod.h"
using namespace stdperson;
void stdperson::PrintMessage(Person p)
{
{
cout<<"*********************************"<
cout<
cout<
cout<<"********************************"<
}
}
#include "onemethod.h"
using namespace stdperson;
void stdperson::PrintMessage(Person p)
{
{
cout<<"*********************************"<
cout<
cout<
cout<<"********************************"<
}
}
5 main.cpp
[cpp]
#include "person.h"
#include "onemethod.h"
using namespace stdperson;
int main()
{
Person p("dd", 12);
cout<
cout<
PrintMessage(p); //条款23 宁以non-member函数代替member函数
system("pause");
return 0;
}
#include "person.h"
#include "onemethod.h"
using namespace stdperson;
int main()
{
Person p("dd", 12);
cout<
cout<
PrintMessage(p); //条款23 宁以non-member函数代替member函数
system("pause");
return 0;
}
//-------------------------------------------------------------------------------------------------------------
尽量使用pass by reference,当然啦pass by reference to const就更好了
[cpp]
ifndef OTHERMETHOD_H
#define OTHERMETHOD_H
#include "person.h"
namespace stdperson
{
void PrintOther(Person p);
}
#endif
#ifndef OTHERMETHOD_H
#define OTHERMETHOD_H
#include "person.h"
namespace stdperson
{
void PrintOther(Person p);
}
#endif
[cpp]
#include "othermethod.h"
namespace stdperson
{
void PrintOther(Person p)
{
cout<<"***************PrintOther*******************"<
cout<
cout<
cout<<"********************************************"<
}
}
#include "othermethod.h"
namespace stdperson
{
void PrintOther(Person p)
{www.2cto.com
cout<<"***************PrintOther*******************"<
cout<
cout<
cout<<"********************************************"<
}
}
如果有一个子类继承了Person,并且Person中的GetName()和GetAge()方法都是virtual的,如果上主函数上如此这般调用,会产生截断的恶果。一直调用的方法都是基类的GetName()和GetAge();要想调用的是子类的GetName()和GetAge()方法,有两种方法,一种是将PrintOther的参数改成指针,另外一种方法就是将参数改成Person &p,改成pass by reference或pass by reference to const