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.0n"; } } void Rectangle::setWidth(double w) { if (w >= 0.0) width = w; else { width = 1.0; cout << "Invalid width. Using a default value of 1.0n"; } } 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