C++——面对对象之基本用法

类的定义

class 类名{

        访问权限:

                属性;

                方法;

}

类的调用

        类名 对象名;

        对象名.方法名();

        对象名.属性名;

示例代码一: 计算圆周长/面积
#define PI 3.14

class Circle {
    public:
        float radius;
        // 获取周长
        float get_ZC(){
            return 2*PI*radius;
        }
        //获取圆的面积
        float get_area(){
            return radius*radius*PI;
        }
};

int main(){
    Circle c1;
    c1.radius = 10.5;
    float zc,area;
    zc = c1.get_ZC();
    area = c1.get_area();
    cout<<"周长:"<< zc<<","<<"面积:"<
示例代码二: 设计学生类修改姓名/电话
class Student{
    public:
        string s_name;
        int s_age;
        int s_gender=0;
    private:
        string s_phone_number;
    public:
        void set_name(string name,int age,string phone_number){
            s_name = name;
            s_age = age;
            s_phone_number=phone_number;
            cout<<"name:"<
 示例代码三: 计算立方体周长/体积(属性私有)
class Cude{
private:
    float m_L;
    float m_W;
    float m_H;
public:
    void set_L(float l){
        m_L = l;
    }
    void set_W(float w){
        m_W = w;
    }
    void set_H(float h){
        m_H = h;
    }
    float get_L(){
        return m_L;
    }
    float get_W(){
        return m_W;
    }
    float get_H(){
        return m_H;
    }
    float get_arc(){
        return (m_L*m_W+m_H*m_L+m_W*m_H)*2;
    }
    float get_area(){
        return m_H*m_L*m_W;
    }
    Cude(float l,float w,float h){
        set_L(l);
        set_W(w);
        set_H(h);
    }
};

int main(){
    Cude cude(2,4,6);
    float arc = cude.get_arc();
    float area = cude.get_area();
    cout<<"arc:"<

你可能感兴趣的:(C/C++,c++,开发语言)