C ++双初始化

时间:2014-03-08 17:23:33

标签: c++

#include <iostream>
#include <math.h>

using namespace std;

class circle
{
public:
    circle();
    circle(double radius);
    double circlerad(void);
    double area(void);
    double circumference(void);

private:
    double rad;

};

circle::circle()
{
    double rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    double rad = radius;
}

double circle::circlerad(void)
{
    return rad;
}

double circle::area(void)
{
    double res;

    res = rad * rad * 3.14;

    return res;
}

double circle::circumference(void)
{
    return (double) rad * 2 * 3.14;
}

double radius(int x1, int y1, int x2, int y2)
{
    double rad = 0;

    double xm, ym;

    xm = (double)(x1 + x2) / 2;
    ym = (double)(y1 + y2) / 2;

    rad = sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));

    return rad;
}

int main(void)
{
    double rad;
    int x1, y1;
    int x2, y2;

    cout << "x1 : ";
    cin >> x1;
    cout << "y1 : ";
    cin >> y1;
    cout << "x2 : ";
    cin >> x2;
    cout << "y2 : ";
    cin >> y2;

    *circle one((double)radius(x1, y1, x2, y2));*

    cout << fixed << one.area() << endl;
    //cout << fixed << one.circumference() << endl;

    return 0;
}

这是我计算圆周面积和周长的代码。

但问题是当我初始化第一个圆圈时,无论半径(x1,y1,x2,y2)值如何,

它始终初始化为-9.2559631349317831e + 061。

2 个答案:

答案 0 :(得分:1)

你没有在这里初始化circle :: rad(而是使用局部变量rad):

circle::circle()
{
    double rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    double rad = radius;
}
你应该做点什么:

circle::circle(): rad(0)
{
}

circle::circle(double radius): rad(radius)
{
}

答案 1 :(得分:1)

double rad声明一个局部变量,它与类成员rad不同。最简单的解决方法:

circle::circle()
{
    rad = 0;
}

circle::circle(double radius)
{
    cout << radius << endl;
    rad = radius;
}