0

我制作了两个 MathUtils.h 文件

#include "iostream"

和 MathUtils.cpp

#include "MathUtils.h"

using namespace std;

//Box class .....................
class Box
{
private:
    double length;   // Length of a box
    double breadth;  // Breadth of a box
    double height;   // Height of a box
public:
    void setParameters(int l,int b,int h);
    int volume();
    int area();
};

void Box::setParameters(int l, int b, int h)
{
    length=l;
    breadth=b;
    height=h;
}

int Box::volume()
{
    return length*breadth*height;
}

int Box::area()
{
    return (2*(length*breadth) + 2*(breadth*height) + 2*(height*length));
}


//sphere class................
class Sphere
{
private:
    double pi=3.14;
    double r;
public:
    void setParameters(int radius);
    int volume();
    int area();
};

void Sphere::setParameters(int radius)
{
    r=radius;
}

int Sphere::volume()
{
    return (4/3)*pi*r*r;
}

int Sphere::area()
{
    return 4*pi*r*r;
}

我们如何在我的项目中使用这个文件可以帮助我。我从来没有在我的项目中使用过 c++ 文件,所以我想知道我们如何在其他 viewController 文件中使用 Box 和 Sphere 类对象。谢谢!。

4

1 回答 1

1

您在 .h 文件中定义您的类。

对于您的示例,请移动:

class Box
{
private:
    double length;   // Length of a box
    double breadth;  // Breadth of a box
    double height;   // Height of a box
public:
    void setParameters(int l,int b,int h);
    int volume();
    int area();
};

class Sphere
{
private:
    double pi=3.14;
    double r;
public:
    void setParameters(int radius);
    int volume();
    int area();
};

mathutils.h并添加#include "mathutils.h"到您的 viewController 文件中。您的 Box 成员函数应该仍然在mathutils.c

然后,您的视图控制器中的函数可以使用它:

{
  Box b;
  b.setParameters(1,2,3);
  int v = b.volume();
  int a = b.area();
}
于 2013-03-08T13:42:21.947 回答