c++学习(类、内联、构造、析构)

版权声明:虽为原创,欢迎转载。 https://blog.csdn.net/m0_37655357/article/details/89153416

分文件组织工程结构:

1、一个包含类定义的头文件,文件名就是自己的类名

#ifndef RECTANGLE_H_INCLUDED
#define RECTANGLE_H_INCLUDED

class Rectangle
{
private:
    float width;
    float length;
    float area;
    char *boxName;

    //函数在类内定义,称为内联函数,不需要作用域分辨符
    //将代码较少的函数定义为内联函数,可以减少函数调用时的开销
    void calcArea(void){area = width * length;}

public:
    //内联构造函数
    Rectangle()
    {
        //构造函数的功能之一,就是初始化默认参数,并进行动态内存分配
        boxName = new char[128];
        cout<<"this is the constructor!\n\n";
    }

    //内联析构函数,释放之前动态申请的空间,进行善后处理
    ~Rectangle()
    {
        delete []boxName;
        cout<<"this is the destructor!\n\n";
    }

    void setBoxName(char *name);
    char *getBoxName(void);
    void setData(float w, float l);
    float getWidth(void);
    float getLength(void);
    float getArea(void);
};

#endif // RECTANGLE_H_INCLUDED

2、一个包含类中方法实现的源文件,文件名也是类名

#include <iostream>
using namespace std;

#include <string.h>
#include "rectangle.h"

void Rectangle::setBoxName(char *name)
{
    strcpy(boxName,name);
}

//返回指针即可,cout会自动输出该字符串所指向的字符。
char *Rectangle::getBoxName(void)
{
    return boxName;
}

void Rectangle::setData(float w, float l)
{
    width = w;
    length = l;
    calcArea();
}

float Rectangle::getLength(void)
{
    return length;
}

float Rectangle::getWidth(void)
{
    return width;
}

float Rectangle::getArea(void)
{
    return area;
}

3、项目实现源文件,文件名可以是自己的工程名,调用类的方法和属性实现自己的功能。

#include <iostream>

using namespace std;

#include "rectangle.h"


int main()
{
    Rectangle Box;
    float myWidth, myLength;

    Box.setBoxName("andrew");
    cout<<"the name of the box is "<<Box.getBoxName();
    cout<<endl<<endl;

    cout<<"please input the length:";
    cin>>myLength;
    cout<<"please input the width:";
    cin>>myWidth;

    Box.setData(myWidth,myLength);
    cout<<"\nthe data of box of your input is:\n";
    cout<<"the length of the box is:"<<Box.getLength()<<endl;
    cout<<"the width of the box is:"<<Box.getWidth()<<endl;
    cout<< "the area of the box is:"<<Box.getArea()<< endl;
    return 0;
}

运行结果:

猜你喜欢

转载自blog.csdn.net/m0_37655357/article/details/89153416