void setRadius(double);
double getArea();
void Circle::setRadius(double r) { radius = r; } double Circle::getArea() { return 3.14 * pow(radius, 2); }可以看到,以上函数实现语句和普通函数看起来是一样的,区别在于,在函数返回类型之后函数名之前,放置了类名和双冒号(::)。:: 符号称为作用域解析运算符。它可以用来指示这些是类成员函数,并且告诉编译器它们属于哪个类。
注意,类名和作用域解析运算符是函数名的扩展名。当一个函数定义在类声明之外时,这些必须存在,并且必须紧靠在函数头中的函数名之前。
以下示例通过对比,清晰说明了当类函数定义在类声明之外时,该如何使用作用域解析运算符:
double getArea () //错误!类名称和作用域解析运算符丢失
Circle :: double getArea () //错误!类名称和作用域解析运算符错位
double Circle :: getArea () //正确
// This program demonstrates a simple class with member functions defined outside the class declaration. #include <iostream> #include <cmath> using namespace std; //Circle class declaration class Circle { private: double radius; // This is a member variable. public: void setRadius(double); // These are just prototypes double getArea(); // for the member functions. }; void Circle::setRadius(double r) { radius = r; } double Circle::getArea() { return 3.14 * pow(radius, 2); } int main() { Circle circle1,circle2; circle1.setRadius(1); // This sets circle1's radius to 1.0 circle2.setRadius(2.5); // This sets circle2's radius to 2.5 cout << "The area of circle1 is " << circle1.getArea() << endl; cout << "The area of circle2 is " << circle2.getArea() << endl; return 0; }程序输出结果为:
The area of circle1 is 3.14
The area of circle2 is 19.625
#include <iostream> using namespace std; // Rectangle class declaration class Rectangle { private: double length; double width; public: void setLength(double); void setWidth(double); double getLength(); double getWidth(); double getArea(); }; //Member function implementation section void Rectangle::setLength(double len) { if (len >= 0.0) length = len; else { length = 1.0; cout << "Invalid length. Using a default value of 1.0\n"; } } void Rectangle::setWidth(double w) { if (w >= 0.0) width = w; else { width = 1.0; cout << "Invalid width. Using a default value of 1.0\n"; } } double Rectangle::getLength() { return length; } double Rectangle::getWidth() { return width; } double Rectangle::getArea() { return length * width; } int main() { Rectangle box; // Declare a Rectangle object double boxLength, boxWidth; //Get box length and width cout << "This program will calculate the area of a rectangle.\n"; cout << "What is the length?"; cin >> boxLength; cout << "What is the width?"; cin >> boxWidth; //Call member functions to set box dimensions box.setLength(boxLength); box.setWidth(boxWidth); //Call member functions to get box information to display cout << "\nHere is the rectangle's data:\n"; cout << "Length: " << box.getLength() << endl; cout << "Width : " << box.getWidth () << endl; cout << "Area : " << box.getArea () << endl; return 0; }程序运行结果:
This program will calculate the area of a rectangle.
What is the length?10.1
What is the width?5
Here is the rectangle's data:
Length: 10.1
Width : 5
Area : 50.5
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有