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