17、C 类构造与静态成员深入解析

C# 类构造与静态成员深入解析

构造函数链与可选参数

在 C# 中,构造函数链是一种实用的技术。以 Motorcycle 类为例:

class Motorcycle
{
    public int driverIntensity;
    public string driverName;

    // Constructor chaining.
    public Motorcycle() {}
    public Motorcycle(int intensity)
        : this(intensity, "") {}
    public Motorcycle(string name)
        : this(0, name) {}

    // This is the 'master' constructor that does all the real work.
    public Motorcycle(int intensity, string name)
    {
        if (intensity > 10)
        {
            intensity = 10;
        }
        driverIntensity = intensity;
        driverName = name;
    }
}

使用 this 关键字进行构造函数链调用并非强制要求,但使用该技术能使类定义更易于维护和简洁。其工作流程如下:
1. 调用需要单

P2911 [USACO08OCT] Bovine Bones G 是洛谷【入门 4】数组中的一道题目。题目描述为 Bessie 喜欢棋盘游戏和角色扮演游戏,她说服 Farmer John 带她去一家爱好商店,在那里她购买了三个骰子用于投掷,这些骰子分别有 S1、S2 和 S3 个面[^1]。 在解题代码方面,有 Java 和 C++ 两种实现。Java 代码通过定义一个长度为 81 的数组统计不同和值出现的次数,通过嵌套循环模拟掷骰子的过程,将每个和值对应的数组元素加 1,同时更新最大出现次数及其对应的和值,最后输出最大出现次数对应的和值[^2]。示例代码如下: ```java import java.util.Scanner; public class P2911_1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int s1 = sc.nextInt(), s2 = sc.nextInt(), s3 = sc.nextInt(); int[] arr = new int[81]; int max = 0; int temp = 0; for (int i = 1; i <= s1; i++) { for (int j = 1; j <= s2; j++) { for (int k = 1; k <= s3; k++) { arr[i + j + k]++; if (temp < arr[i + j + k]) { max = i + j + k; temp = arr[i + j + k]; } } } } System.out.println(max); sc.close(); } } ``` C++ 代码同样使用数组统计和值出现的次数,先通过三重循环模拟掷骰子得到所有可能的和值并更新对应次数,再遍历所有可能的和值范围,找出出现次数最多且和值最小的结果并输出[^3]。示例代码如下: ```cpp #include<bits/stdc++.h> using namespace std; int s1, s2, s3, res; int cnt[20000]; int maxn = -1e9; int main() { scanf("%d%d%d", &s1, &s2, &s3); for (int i = 1; i <= s1; ++i) { for (int j = 1; j <= s2; ++j) { for (int k = 1; k <= s3; ++k) { cnt[i + j + k]++; } } } for (int i = 3; i <= s1 + s2 + s3; ++i) { if (cnt[i] > maxn) maxn = cnt[i], res = i; } printf("%d", res); return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值