• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wukong04

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

构造函数中可以使用默认参数

#include <iostream>
using namespace std;
class Box
{
public:
Box(int x = 0, int y = 0, int z = 0);  //声明构造函数时指定默认参数
void area();
void volume();
private:
int height;
int width;
int lendth;
};
Box::Box(int x, int y, int z)   //定义构造函数时可以不指定参数
{
height = x;
width = y;    //给私有成员变量赋值
lendth = z;
}
void Box::area()
{
int s;
s = height * width * lendth;
cout << "s="<< s << endl;
}
void Box::volume()
{
int v;
v = 2 * (height * width) + 2 * (height * lendth) + 2 * (width * lendth);
cout << "v=" << v << endl;
}
int main()
{
Box box1(0, 0, 0);
int x, y, z;
x = 0; y = 0; z = 0;
cout << "x=" << x << " " << "y = " << y << " " << "z = " << z << endl;
box1.area();
box1.volume();
Box box2(10, 0, 0);
x = 10; y = 0; z = 0;
cout << "x=" << x << " " << "y = " << y << " " << "z = " << z << endl;
box2.area();
box2.volume();
Box box3;
x = 10; y = 20; z = 0;
cout << "x=" << x << " " << "y = " << y << " " << "z = " << z << endl;
box3.area();
box3.volume();
Box box4(10, 20, 30);
x = 10; y = 20; z = 30;
cout << "x=" << x << " " << "y = " << y << " " << "z = " << z << endl;
box4.area();
box4.volume();
return 0;
}

posted on 2023-03-22 20:40  悟空+  阅读(102)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3