1.6 Extend 繼承合約

閱讀時間約 3 分鐘
extend

extend

這個合約將管理校慶運動會的基本信息和操作,並且包含了特定的運動會活動,如校內運動會的規則和獎勵制度。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract SportsFestival {
struct Participant {
string name;
uint age;
string sport;
}

mapping(uint => Participant) public participants;
uint public participantCount;

function addParticipant(string memory name, uint age, string memory sport) public {
participantCount++;
participants[participantCount] = Participant(name, age, sport);
}

function getParticipant(uint id) public view returns (string memory name, uint age, string memory sport) {
Participant memory participant = participants[id];
return (participant.name, participant.age, participant.sport);
}
}

contract SchoolSportsFestival is SportsFestival {
mapping(string => uint) public scores;

function addScore(string memory sport, uint score) public {
scores[sport] += score;
}

function getScore(string memory sport) public view returns (uint) {
return scores[sport];
}
}
  • SportsFestival合約定義了運動會的基本結構和操作,包括添加參賽者和查詢參賽者的信息。
  • SchoolSportsFestival合約繼承自SportsFestival,並添加了一個新的映射scores來追蹤各種運動的分數。這種繼承模式允許我們將通用的運動會管理功能封裝在基礎合約中,並在衍生合約中添加或修改特定的行為,如校內運動會的獎勵制度。
    尋大神腳印, 亦步亦趨。
    留言0
    查看全部
    發表第一個留言支持創作者!
    從 Google News 追蹤更多 vocus 的最新精選內容