假设我有一个 X 类(Xh):
class X {
private:
unsigned unitsSold = 0;
double revenue = 0.0;
public:
double avgPrice();
}
avgPrice()
应该定义哪种方式?
选项 1(课堂):
Xh
class X {
private:
unsigned unitsSold = 0;
double revenue = 0.0;
public:
double avgPrice() {
return unitsSold ? revenue / unitsSold : 0;
}
}
选项 2(与类在同一文件中,但在类定义之外):
Xh
class X {
private:
unsigned unitsSold = 0;
double revenue = 0.0;
public:
double avgPrice();
}
inline double X::avgPrice() {
return unitsSold ? revenue / unitsSold : 0;
}
或选项 3(在单独的头文件中):
Xh:
class X {
private:
unsigned unitsSold = 0;
double revenue = 0.0;
public:
double avgPrice();
}
X-inl.h:
#include "X.h"
inline double X::avgPrice() {
return unitsSold ? revenue / unitsSold : 0;
}