15-Solidity8.0构造函数&事件

Solidity8.0

15-Solidity8.0构造函数&事件


在这里插入图片描述


前言

构造函数
constructor是在合约创建时执行的可选函数。

事件
Events允许登录到以太坊区块链。事件的一些用例是:

监听事件和更新用户界面
一种廉价的存储方式
// 事件声明
// 最多可以有3个参数被索引。
// 被索引的参数可以帮助你通过被索引的参数过滤日志


一、Solidity构造函数&事件

1.构造函数&事件

代码如下(示例):

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

// Base contract X
contract X {
    
    
    string public name;
    event AnotherLog();
	event Log(address indexed sender, string message);
    constructor(string memory _name) {
    
    
        name = _name;
    }
    
	function test() public {
    
    
        emit Log(msg.sender, "Hello World!");
        emit AnotherLog();
    }
}

// Base contract Y
contract Y {
    
    
    string public text;

    constructor(string memory _text) {
    
    
        text = _text;
    }
}

// There are 2 ways to initialize parent contract with parameters.
// Pass the parameters here in the inheritance list.
contract B is X("Input to X"), Y("Input to Y") {
    
    

}

contract C is X, Y {
    
    
    // Pass the parameters here in the constructor,
    // similar to function modifiers.
    constructor(string memory _name, string memory _text) X(_name) Y(_text) {
    
    }
}

// Parent constructors are always called in the order of inheritance
// regardless of the order of parent contracts listed in the
// constructor of the child contract.

// Order of constructors called:
// 1. X
// 2. Y
// 3. D
contract D is X, Y {
    
    
    constructor() X("X was called") Y("Y was called") {
    
    }
}

// Order of constructors called:
// 1. X
// 2. Y
// 3. E
contract E is X, Y {
    
    
    constructor() Y("Y was called") X("X was called") {
    
    }
}

总结

日拱一卒。

猜你喜欢

转载自blog.csdn.net/yyjava/article/details/125294992