LoginSignup
1
0

More than 5 years have passed since last update.

【Blockchain】継承

Last updated at Posted at 2019-04-08

Solidityで書くSmart Contractsは、オブジェクト思考言語ですので、継承を実現することができます。

継承する基底Contractを作成

まずは、継承する基底Contractを作ってみましょう。

前回のサンプルで作りましたSmart Contractは、オーナーのアドレスを属性に保持し、オーナーであるかの確認をするmodifierを作りました。
これらの機能は、どのSmart Contractでも必要なものです。
そこで、その機能を一つのContractに作って、それを継承するようにしましょう。

Remixの左側に (+) ボタンがありますので、それをクリックします。
ファイル名を Ownable.sol にします。
そして、下記のプログラムを入力しましょう。

pragma solidity ^0.4.24;

contract Ownable {

    address private owner;

    constructor() public {
        owner = msg.sender;
    }

    modifier isOwner() {
        require(owner == msg.sender);
        _;
    }
}

継承して派生Contractを作成

上記で作成したOwnableをMessageStoreに継承してみましょう。

pragma solidity ^0.4.24;

import "./Ownable.sol";

contract MessageStore is Ownable {

    string private message;

    function setMessage(string newMessage) public isOwner {
        message = newMessage;
    }

    function getMessage() public view returns (string) {
        return message;
    }
}

インポートは、 import "Ownable.sol"; で行います。
そして、Contractの定義に is Ownable を追加します。
これで、オーナーのアドレスを保持する機能とmodifier修飾子である isOwner も使えるようになります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0