1)当我们也可以内联定义它时,在以下情况下,作用域解析运算符有什么用?
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
double Box::getVolume(void)
{
return length * breadth * height;
}
2)此外,该行的语义double Box::getVolume(void)
令人困惑。为什么不能呢double getVolume(void)::Box
?这背后有一些历史吗?
1)当我们也可以内联定义它时,在以下情况下,作用域解析运算符有什么用?
在您的示例中,在类中定义方法时不需要范围解析运算符:
class Box
{
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void)// Returns box volume
{
return length * breadth * height;
}
};
但是,当在类之外定义函数时,程序员需要一种将函数与给定类关联的方法。此方法需要区分类方法和独立函数。因此范围解析算子。
2)此外,双线Box :: getVolume(void)的语义令人困惑。为什么不能呢:double getVolume(void):: Box。这背后有一些历史吗?
实际上,当您考虑独立函数的声明语法时,该语法不会引起混淆:
return_type function_name(function_parameters);
包含的名称空间或类与函数名称相关联,因此语法为:
return type class_name::function_name(function_parameters);
如果您以不同的方式排列各部分,则定义和声明可能会减少混乱:
double
Box ::
getVolume(void)
{
return height * length * depth;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句