12.10 C语言作业3



课上类的三个练习题的构造函数

cpp 复制代码
#include <iostream>
using namespace std;
class Rec
{
   int length;
   int width;
public:
   Rec(int length,int width):length(length),width(width){}
   void set_length(int l);
   void set_width(int 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()
{
    return length;   //将长度的值返回给调用处
}
int Rec::get_width()
{
    return width;
}
void Rec::show()
{
    cout << "周长为:" << 2*(length+width) << endl;
    cout << "面积是:" << length*width << endl;
}
int main()
{
    //实例化类对象
    Rec r1(4,5);
    r1.set_length(2);
    r1.set_width(3);
    int a = r1.get_width();
    cout << a << endl;
    r1.show();
    return 0;
}
cpp 复制代码
#include <iostream>
using namespace std;
class Cir
{
    int r;
public:
    Cir(int &r):r(r){}
    void set_r(int r);  //设置私有属性r的值
    void show(double PI=3.14);   //参数有默认值3.14
};
void Cir::set_r(int r1)
{
    r = r1;
}
void Cir::show(double PI)
{
    cout << "周长:" << 2*r*PI << endl;
    cout << "面积:" << r*r*PI << endl;
}
int main()
{
    int r =1;
    Cir c1(r);
    c1.show();
    c1.set_r(4);
    c1.show();
    return 0;
}
cpp 复制代码
#include <iostream>

using namespace std;

//定义了一个Stu类
class Car
{
    string color;
    string brand;
    int speed;
public:
    //为类中的私有成员获取值
    Car(string color,string brand,int speed):color(color),brand(brand),speed(speed){}
    void display();//公有的成员函数
    void acc(int a);
    void set(string p,string color,int s);
};
void Car::set(string p,string c,int s)
{
    brand = p;
    color = c;
    speed = s;

}
void Car::acc(int s1)
{
    speed += s1;
}
void Car::display()
{
    cout<< "品牌:"<<brand;
    cout<< "颜色:"<<color;
    cout<< "速度:"<<speed<<"km/h";
}
int main()
{
    Car s1("紫色","小米",99);
    s1.display();
    cout<<endl;
    s1.set("奥迪","黑色",100);
    s1.display();
    s1.acc(10);
    s1.display();
    return 0;
}
相关推荐
夏鹏今天学习了吗10 分钟前
【LeetCode热题100(39/100)】对称二叉树
算法·leetcode·职场和发展
·心猿意码·1 小时前
C++Lambda 表达式与函数对象
开发语言·c++
天选之女wow1 小时前
【代码随想录算法训练营——Day34】动态规划——416.分割等和子集
算法·leetcode·动态规划
小莞尔1 小时前
【51单片机】【protues仿真】基于51单片机全自动洗衣机系统
c语言·单片机·嵌入式硬件·物联网·51单片机
Boop_wu2 小时前
[数据结构] 哈希表
算法·哈希算法·散列表
Mingze03142 小时前
C语言四大排序算法实战
c语言·数据结构·学习·算法·排序算法
小龙报3 小时前
《彻底理解C语言指针全攻略(3)》
c语言·开发语言·windows·git·创业创新·学习方法·visual studio
棉猴3 小时前
GESP C++等级认证三级15-原码反码补码2-2
开发语言·c++·gesp·c++三级·等级认证·原码反码补码
IT古董3 小时前
【第五章:计算机视觉-项目实战之生成式算法实战:扩散模型】3.生成式算法实战:扩散模型-(3)DDPM模型训练与推理
人工智能·算法·计算机视觉
独自破碎E3 小时前
Leetcode2166-设计位集
java·数据结构·算法