关于C++中类的成员函数实现的位置有关问题

关于C++中类的成员函数实现的位置问题
关于C++中类的成员函数实现的位置问题
  各位大神,你们好,本人系刚 学C++的菜鸟,用的是清华大学出版的《C++语言程序设计》第三版,在讲类的成员函数的声明和实现时,书上(95页)是这样说的“函数的原型声明要写在类体中,原型说明了函数的参数表和和返回值。而函数的具体实现是写在类之外的”然后实现的具体形式是书上给出的 返回值类型 类名::函数成员名(参数表)
{
  函数体
}
这里它对类的成员函数 的实现是说要写在 类之外的,但我发现在书本之后的例题4-2(本篇文章的例1)中,给出的类的成员函数GetX()和 GetY()的实现不就是写在类体之内了吗?
例1
#include<iostream>
using namespace std;
class Point
{
public:
Point(int xx=0,int yy=0){X=xx;Y=yy;}
Point(Point &p);
int GetX(){return X;}
int GetY(){return Y;}
private:
int X,Y;
};
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"拷贝构造函数被调用"<<endl;
}
void fun1(Point p)
{
cout<<p.GetX()<<endl;
}
Point fun2()
{
Point A(1,2);
return A;
}
int main()
{
Point A(4,5);
Point B(A);
cout<<B.GetX()<<endl;
fun1(B);
B=fun2();
cout<<B.GetX()<<endl;
}
然后,我把类的成员函数GetX()和GetY()放到类体之外 实现,也成功实现了相同的结果,修改后的程序如下例2,就把GetX()和GetY()放到类体之外 实现而已,其他都没改。两种结果都相同,都没有错误,所以我就有个猜想:是不是类的成员函数,在类里声明的时候也能同时去实现,而不是向书上说的一样!于是我又在书上找了个例子(下文给出的例3,书上的例4-1),它的类的成员函数void SetTime(int NewH=0,int NewM=0,int NewS=0)声明是放在类体之外的,然后我会了验证我上面的猜想,我把例3做了一些修改,把SetTime函数放到类体中去实现,看能否成功,如下文的例4,发现程序运行正常,结果和例3一样!由此我这里暂得出:类的成员函数也可以放在类体中去实现的结论。由于刚接触C++,很多地方都还不懂,有些问题的认识可能很无知,所以这里写这个帖子,是想请各位大神们帮看看我这个结论是否有误,小弟不胜感激!谢谢啦!

例2
#include<iostream>
using namespace std;
class Point
{
public:
Point(int xx=0,int yy=0){X=xx;Y=yy;}
Point(Point &p);
int GetX();
int GetY();
private:
int X,Y;
};
Point::Point(Point &p)
{
X=p.X;
Y=p.Y;
cout<<"拷贝构造函数被调用"<<endl;
}
int Point::GetX()
{
return X;
}
int Point::GetY()
{
return Y;
}
void fun1(Point p)
{
cout<<p.GetX()<<endl;
}
Point fun2()
{
Point A(1,2);
return A;
}
int main()
{
Point A(4,5);
Point B(A);
cout<<B.GetX()<<endl;
fun1(B);
B=fun2();
cout<<B.GetX()<<endl;
}

例3
#include<iostream>
using namespace std;
class Clock
{
public:
void SetTime(int NewH=0,int NewM=0,int NewS=0);
void ShowTime();
private:
int Hour,Minute,Second;
};
//时钟类成员函数的具体实现
void Clock::SetTime(int NewH,int NewM,int NewS)
{
Hour=NewH;
Minute=NewM;
Second=NewS;
}
inline void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}
int main()
{
Clock myClock;
cout<<"First time set and output:"<<endl;
myClock.SetTime();
myClock.ShowTime();
cout<<"Second time set and output:"<<endl;
myClock.SetTime(8,30,30);
myClock.ShowTime();
}

例4
#include<iostream>
using namespace std;
class Clock
{
public:
void SetTime(int NewH=0,int NewM=0,int NewS=0)
{
Hour=NewH;
Minute=NewM;
Second=NewS;
}
void ShowTime();
private:
int Hour,Minute,Second;
};
//时钟类成员函数的具体实现
/*void Clock::SetTime(int NewH,int NewM,int NewS)
{
Hour=NewH;
Minute=NewM;
Second=NewS;
}*/
inline void Clock::ShowTime()
{
cout<<Hour<<":"<<Minute<<":"<<Second<<endl;
}
int main()
{
Clock myClock;
cout<<"First time set and output:"<<endl;
myClock.SetTime();
myClock.ShowTime();
cout<<"Second time set and output:"<<endl;
myClock.SetTime(8,30,30);
myClock.ShowTime();
}

------解决方案--------------------