3分钟Solidity: 4.9 构造函数

35 阅读1分钟

如需获取本内容的最新版本,请参见 Cyfrin.io 上的Constructor(代码示例)

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

以下是向构造函数传递参数的示例。

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

// 基类合约 X
contract X {
    string public name;

    constructor(string memory _name) {
        name = _name;
    }
}

// 基类合约 Y
contract Y {
    string public text;

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

// 有两种方法可以使用参数初始化父合约。

// 在继承列表中传递参数。
contract B is X("Input to X"), Y("Input to Y") {}

contract C is X, Y {
    // 在此处的构造函数中传递参数,类似于函数修饰符。
    constructor(string memory _name, string memory _text) X(_name) Y(_text) {}
}

// 父构造函数总是按照继承顺序被调用, 不论父合约在子合约构造函数中的列出顺序如何
// 构造函数调用顺序:
// 1. X
// 2. Y
// 3. D
contract D is X, Y {
    constructor() X("X was called") Y("Y was called") {}
}

// 构造函数调用顺序:
// 1. X
// 2. Y
// 3. E
contract E is X, Y {
    constructor() Y("Y was called") X("X was called") {}
}

Remix Lite 尝试一下

solidity-constructor

END