C++类方法

Luc*_*cas 5 c++ methods netbeans class object

我正在学习C++,我有一个问题.

我在Netbeans中创建了一个类,它创建了Rectangle.h和Rectangle.cpp.我试图添加输出矩形lw变量的面积和周长的方法.我不知道如何在类中创建方法以及如何将它们合并到Rectangle.h文件中.

这是我正在尝试做的事情:

Rectangle rct;
rct.l = 7;
rct.w = 4;
cout << "Area is " << rct.Area() << endl;
cout << "Perim is " << rct.Perim() << endl;
Run Code Online (Sandbox Code Playgroud)

有人可以解释如何做到这一点?我很困惑.

谢谢,

卢卡斯

gri*_*fos 9

在.h文件中你有类定义,你写下成员函数的成员函数(通常作为原型)

在.cpp文件中,您声明方法体.例:

rectangle.h:

class rectangle
{
    public:
    // Variables (btw public member variables are not a good 
    //   practice, you should set them as private and access them 
    //   via accessor methods, that is what encapsulation is)
    double l;
    double w;

    // constructor
    rectangle();
    // Methods
    double area();
    double perim();
};
Run Code Online (Sandbox Code Playgroud)

rectangle.cpp:

#include "rectangle.h" // You include the class description

// Contructor
rectangle::rectangle()
{
   this->l = 0;
   this->w = 0;
}

// Methods
double rectangle::area()
{
   return this->w * this->l;
}

double rectangle::perim()
{
   return 2*this->w + 2*this->l;
}
Run Code Online (Sandbox Code Playgroud)

但是像gmannickg说你应该读一本关于c ++或真正的教程的书,这将解释你的语法是如何工作的.面向对象编程(如果你不熟悉它)