C++ 类实现算长方体体积


类内声明,类外定义

使用类内的成员函数给类内的私有成员赋值,并且成员函数在类内声明,类外定义

#include <iostream>
using namespace std;
class cft
{
    private:
        float length;
        float width;
        float heigth;
    public:
        void set_length ();
        void set_width ();
        void set_heigth ();
        void show_tj ();
}; 

void cft::set_length()
{
    cin>>length;
}
void cft::set_width()
{
    cin>>width;
}
void cft::set_heigth()
{
    cin>>heigth;
}
void cft::show_tj()
{
    cout<<length*width*heigth<<endl;
}

main()
{
    cft a;
    a.set_length();
    a.set_width();
    a.set_heigth();
    a.show_tj();
    return 0;
}

 

构造函数初始化

使用构造函数给长宽高赋值,并计算体积

#include <iostream>
using namespace std;
class cft
{
    private:
        float length;
        float width;
        float heigth;
    public:
        cft (float,float,float);
        void show_tj ();
}; 

cft::cft (float a,float b,float c)
{
    length=a;width=b;heigth=c;
}
void cft::show_tj()
{
    cout<<length*width*heigth<<endl;
}

main()
{
    float a,b,c;
    cin>>a>>b>>c;
    cft t(a,b,c);
    t.show_tj();
    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM