C++day3

1、把课上类的三个练习题的构造函数写出来

cpp 复制代码
#include <iostream>
#include <cstring>

using namespace std;

class Car
{
    string color;
    string brond;
    double speed;
public:
    Car(string c,string b,double s):color("black"),brond("Benz"),speed(180.9)
    {
        color = c;
        brond = b;
        speed = s;
        cout << "Car的有参构造" << endl;
    }
    //无参时使用默认参数
    Car():color("black"),brond("Benz"),speed(180.9){}

      void display();
      void acc(int a);
};


void Car::display()
{
    cout << "汽车品牌:" << brond << endl;
    cout << "汽车颜色:" << color << endl;
    cout << "速度:" << speed << "km/h" << endl;
}

void Car::acc(int a)
{
    speed += a;
}
int main()
{
    //有参构造函数
    Car c1("white","buick",50.5);

    c1.display();
    c1.acc(5);
    
    c1.display();
    Car c3;
    c3.display();


    return 0;
}
cpp 复制代码
#include <iostream>

using namespace std;
class Curcle
{
    int radius;
public:
    Curcle(int r):radius(5)
    {
        radius = r;
    }
    Curcle():radius(5){}
    void show(double PI=3.14);
};


void Curcle::show(double PI)
{

    double perimeter = 2 * PI * radius;
    double area = PI * radius * radius;
    cout << "圆的周长 = " << perimeter << endl;
    cout << "圆的面积 = " << area << endl;
}

int main()
{
    Curcle s1(3);
    s1.show();

    Curcle s2;
    s2.show();
    return 0;
}
cpp 复制代码
#include <iostream>

using namespace std;
class Rec
{
    int length;
    int width;
public:
//    void set_length(int l);
//    void set_width(int w);
    Rec(int l,int w)
    {
        length = l;
        width = w;
    }
    int get_length();
    int get_width();
    void show();
};

//void Rec::set_length(int l)
//{
//    length = l;
//}

//void Rec::set_width(int w)
//{
//    width = w;
//}

int Rec::get_length()
{
    cout << "length = " << length << endl;
    return length;
}

int Rec::get_width()
{
    cout << "width = " << width << endl;
    return width;
}

void Rec::show()
{
    cout << "s = " << length * width << endl;
}

int main()
{
    Rec s1(5,4);

//    s1.set_length(5);
//    s1.set_width(4);
    int l = s1.get_length();
    int w = s1.get_width();
    s1.show();

    return 0;
}

Xmind

相关推荐
算法鑫探1 分钟前
算法中的二分法(二分查找)详解及示例
c语言·数据结构·算法·新人首发
艾莉丝努力练剑7 分钟前
【Linux加餐】mmap文件映射
linux·运维·服务器·c语言·c++·学习
DS数模8 分钟前
2026年Mathorcup数学建模竞赛A题思路解析+代码+论文
开发语言·数学建模·matlab·mathorcup·妈妈杯·2026妈妈杯
叶子野格12 分钟前
《C语言学习:编程例题》8
c语言·开发语言·c++·学习·算法·visual studio
Java面试题总结13 分钟前
Python 入门(四)- Openpyxl 操作 Excel 教程
开发语言·python·excel
澈20714 分钟前
排序算法入门:冒泡、选择、插入排序详解
数据结构·算法·排序算法
6Hzlia17 分钟前
【Hot 100 刷题计划】 LeetCode 152. 乘积最大子数组 | C++ 动态规划 (绝妙 swap 翻转技巧)
c++·leetcode·动态规划
smj2302_7968265218 分钟前
解决leetcode第3901题好子序列查询
python·算法·leetcode
gCode Teacher 格码致知19 分钟前
Javascript提高:Math.round 详解-由Deepseek产生
开发语言·javascript
_深海凉_20 分钟前
LeetCode热题100-每日温度
算法·leetcode·职场和发展