const 成员变量只能在类的初始化列表中初始化
Circle(double radius = 0)
:Pi(3.14)
{
//Pi =3.14;
this->radius = radius;
}
const double Pi ;
该成 static const double Pi ;
然后将构造函数中的Pi = 3.14;删除
在类里面加一句
const double Circle::Pi = 3.14;
具体原因详见effective c++第一章第一节 Prefer const and inline to #define
#include
using namespace std;
class Circle{
public:
Circle(double radius = 0, const double a = 3.14) : radius(radius) , Pi(a)
//const数据成员必须在构造函数初始化列表中初始化
{
}
double getArea(){
return Pi* radius* radius;
}
double getCircumference(){
return 2*Pi* radius;
}
private:
const double Pi ;
double radius ;
};
int main(int argc, char *argv[])
{
cout << "Enter a radius: ";
double Radius = 0;
cin >> Radius;
Circle MyCircle(Radius);
cout << "Circumference = " << MyCircle.getCircumference() << endl;
cout << "Area = " << MyCircle.getArea() << endl;
return 0;
}
我也是初学者,只知道怎么改对,具体原理不清楚,把PI放在类的外面,或者别把PI设成const就行了