You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart语言:如何在Room类中实例化四个Wall类(不使用List)

在Room类中创建四个Wall实例(不使用List)

对于刚接触面向对象编程的你来说,直接给Room类定义四个独立的Wall类型属性是最直观的方案,每个属性对应房间的一面墙(比如北、南、东、西墙),这样代码可读性强,也贴合现实场景的逻辑。

实现步骤

  1. 在Room类中声明四个Wall类型的成员变量,分别对应四面墙
  2. 通过构造函数初始化这四个Wall实例(支持默认值或外部传入自定义尺寸的墙)
  3. 可选:添加方法计算所有墙面的总面积,方便使用

修改后的完整代码

void main() {
  // 自定义四面墙的尺寸
  Wall northWall = Wall(height: 3.5, width: 5);
  Wall southWall = Wall(height: 3.5, width: 5);
  Wall eastWall = Wall(height: 3.5, width: 4);
  Wall westWall = Wall(height: 3.5, width: 4);

  // 创建房间并传入自定义墙面
  Room myBedroom = Room(
    northWall: northWall,
    southWall: southWall,
    eastWall: eastWall,
    westWall: westWall,
  );

  // 输出每面墙的面积和总墙面面积
  print("北墙面积:${myBedroom.northWall.totalArea}");
  print("南墙面积:${myBedroom.southWall.totalArea}");
  print("东墙面积:${myBedroom.eastWall.totalArea}");
  print("西墙面积:${myBedroom.westWall.totalArea}");
  print("房间总墙面面积:${myBedroom.totalWallArea}");

  // 也可以直接创建使用默认尺寸墙面的房间
  Room defaultRoom = Room();
  print("默认房间单墙面积:${defaultRoom.northWall.totalArea}");
}

class Room {
  // 定义四个独立的Wall属性,对应四面墙
  final Wall northWall;
  final Wall southWall;
  final Wall eastWall;
  final Wall westWall;

  // 构造函数:支持外部传入自定义墙面,否则使用默认尺寸的Wall
  Room({
    Wall? northWall,
    Wall? southWall,
    Wall? eastWall,
    Wall? westWall,
  })  : northWall = northWall ?? Wall(),
        southWall = southWall ?? Wall(),
        eastWall = eastWall ?? Wall(),
        westWall = westWall ?? Wall();

  // 计算所有墙面的总面积(getter方法,像访问属性一样使用)
  double get totalWallArea {
    return northWall.totalArea +
        southWall.totalArea +
        eastWall.totalArea +
        westWall.totalArea;
  }
}

class Wall {
  double height;
  double width;
  late double totalArea;
  
  Wall({
     this.height = 1,
     this.width = 1,
  }) {
    getAreaTotal();
  }
  
  void getAreaTotal(){
    totalArea = height * width;
  }
}

代码说明

  • 每个Wall实例都有明确的命名(northWall、southWall等),你可以直接通过Room对象访问任意一面墙的属性,比如myBedroom.northWall.height
  • 构造函数使用??运算符实现“如果外部没有传入墙面,就创建默认尺寸的Wall”的逻辑
  • totalWallArea是一个getter方法,无需手动调用,访问时会自动计算总面积

内容的提问来源于stack exchange,提问作者Lucas Barreto Luz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:40:26