C++作业3(类)

1、思维导图

2、类中存在引用成员情况下有参构造

cpp 复制代码
#include <iostream>

using namespace std;
class Cy
{
    float &r;
public:
    Cy(float &r):r(r){
        cout<<"类中存在引用成员情况下有参构造"<<endl;
    };
    float  set_r(float);
    void show();
};
float Cy::set_r(float a)
{
    r=a;
    cout<<"半径r为"<<r<<endl;
    return r;
}

void Cy::show()
{
    float Pi=3.14;
    float S=Pi*r*r;
    cout<<"面积为"<<S<<endl;
    float C=2*Pi*r;
    cout<<"周长为"<<C<<endl;
}
int main()
{
    float r=2.0;
    Cy s1(r);
     s1.show();
    s1.set_r(1);
    s1.show();
    return 0;
}

3、类中存在const修饰成员情况下有参构造

cpp 复制代码
#include <iostream>
using namespace std;
class Rec
{
    const int length;
    int width;
public:
    //有参构造函数
    Rec(int length,int width):length(length),width(width){
        cout<<"类中存在const修饰成员情况下有参构造"<<endl;
    };
    void set_length(int );
    void set_width(int );
    int get_length();
    int get_width();
    void show();
};
void Rec::set_length(int a)
{
  //  length=a;
}
void Rec::set_width(int b)
{
    width=b;
}
int Rec::get_length()
{
    cout<<"长度为"<<length<<endl;
    return length;
}
int Rec::get_width()
{
     cout<<"宽度为"<<width<<endl;
    return width;
}
void Rec::show()
{
    int S=width*length;
    int C=2*width+2*length;
    cout<<"面积为"<<S<<endl;
    cout<<"周长为"<<C<<endl;
}
int main()
{
     Rec s1(4,3);
     //s1.set_length(3);
     s1.set_width(2);
     s1.get_length();
     s1.get_width();
     s1.show();
    return 0;
}

4、一般情况下有参构造

cpp 复制代码
#include <iostream>

using namespace std;
class Car
{
    string color;
    string brand ;
    int speed;
public:
    Car(string color,string brand,int speed):color(color),brand(brand),speed(speed){
        cout<<"一般情况下有参构造"<<endl;
    }
    void set(string,string,int);
    void display();
    void acc(int a);

};
void Car::set(string s1,string s2,int c )
{
    color=s1;
    brand=s2;
    speed=c;

}
void Car::display()
{
    cout<<"汽车颜色为"<<color<<endl;
    cout<<"汽车品牌为"<<brand<<endl;
    cout<<"汽车速度为"<<speed<<endl;
}
void Car::acc(int a)
{
    while(speed<=120)
    {
        speed+=a;
        cout<<"汽车加速中,当前速度为>>>"<<speed<<endl;
    }
    cout<<"汽车已到最高速度120>>>"<<endl;


}
int main()
{
    Car p1("red","奥迪",120);
    p1.display();

    p1.set("bule","五菱",100);
    p1.display();
    p1.acc(10);
    return 0;
}
相关推荐
march of Time10 分钟前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone
24K纯学渣32 分钟前
Python编码格式化之PEP8编码规范
开发语言·ide·python·pycharm
怒视天下34 分钟前
零基础玩转Python生物信息学:数据分析与算法实现
开发语言·python
GISer_Jing1 小时前
Three.js中AR实现详解并详细介绍基于图像标记模式AR生成的详细步骤
开发语言·javascript·ar
委婉待续1 小时前
Qt的学习(一)
开发语言·qt·学习
笨笨马甲1 小时前
Qt Quick Layout功能及架构
开发语言·qt
Dovis(誓平步青云)1 小时前
探索C++标准模板库(STL):String接口的底层实现(下篇)
开发语言·c++·stl·string
海棠一号1 小时前
JAVA理论第五章-JVM
java·开发语言·jvm
草莓熊Lotso2 小时前
【数据结构初阶】--算法复杂度的深度解析
c语言·开发语言·数据结构·经验分享·笔记·其他·算法
KyollBM2 小时前
【CF】Day75——CF (Div. 2) B (数学 + 贪心) + CF 882 (Div. 2) C (01Trie | 区间最大异或和)
c语言·c++·算法