Circle circle1, circle2;
它们是 Circle 类的两个不同实例,被分配了不同的内存,以保存各个对象成员变量中存储的值。cout << city.length() << endl;
以下语句可以调用 circle1 和 circle2 对象的 setRadius 函数:
circle1.setRadius (1.0) ; //该语句可以将circle1的半径设置为1.0
circle2.setRadius (2.5) ; //该语句可以将circle2的半径设置为2.5
circle1.radius = 1.0;
circle2.radius = 2.5;
cout << "The area of circlel is " << circle1.getArea() << endl;
cout << "The area of circle2 is " << circle2.getArea() << endl;
#include <iostream> #include <cmath> using namespace std; //Circle class declaration class Circle { private: double radius; public: void setRadius(double r) { radius = r; } double getArea() { return 3.14 * pow(radiusA 2); } }; int main() { // Define 2 Circle objects Circle circle1, circle2; // Call the setRadius function for each circle circle1.setRadius(1); // This sets circlel's radius to 1.0 circle2.setRadius(2.5); // This sets circle2's radius to 2.5 // Call the getArea function for each circle and // display the returned result 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
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有