C++关于类成员函数定义位置区别(2)
C++关于类成员函数定义位置区别
类成员包括数据成员(一般private)和成员函数(一般public)。成员函数可以访问类私有数据成员
将成员函数定义在类内:
代码示例:
//student.h
class student
{
private:
double height;
double weight;
public:
student(double h,double w);
void show()
{
cout<<'height='<<height<<endl;
cout<<'weight='<< weight <<endl;
}
};//因为是类声明所以有;
解释:定义在类声明内,默认是inline函数,不需要再添加其他关键字(如inline,::等)
写进类声明文件中:
代码示例:
//student.h
class student
{
private:
double height;
double weight;
public:
student(double h,double w);
void show();//声明函数,有;
};
inline void show()//定义函数,没有;
{
cout<<'height='<<height<<endl;
cout<<'weight='<< weight <<endl;
}//定义函数,没有;
说明:需要添加inline关键字
单独写进类成员函数实现文件中(.cpp)
代码示例:
//student.h
class student
{
private:
double height;
double weight;
public:
student(double h,double w);
void show();
};
//student.cpp
student::student(double h,double w)
{
weight=w;
height=h;
}
void student:: show()
{
cout<<'height='<<height<<endl;
cout<<'weight='<< weight <<endl;
}
解释:需要标注类作用域符号::
浙公网安备 33010602011771号