Skip to content

Latest commit

 

History

History
60 lines (42 loc) · 1.78 KB

22 构造函数.md

File metadata and controls

60 lines (42 loc) · 1.78 KB

构造函数(Constructor)

构造函数是在合约创建时执行的函数。它用于初始化合约的数据和状态。

以下示例演示如何使用构造函数设置合约状态。

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

contract Constructor {
    uint256 public myUint;

    constructor(uint256 _myUint) {
        myUint = _myUint;
    }
}
  • constructor 关键字用于定义构造函数。
  • _myUint 参数传递给构造函数来设置 myUint 变量的值。

使用 Remix 部署合约并通过参数设置 myUint 的值。

constructor-remix

现在,我们可以检索 myUint 的值。

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

contract Constructor {
    uint256 public myUint;

    constructor(uint256 _myUint) {
        myUint = _myUint;
    }
}

contract CallerContract {
    function getMyUint(uint256 _myUint) public view returns (uint256) {
        Constructor myContract = new Constructor(_myUint);
        return myContract.myUint();
    }
}
  • 在上面的示例中,我们定义了另一个名为 CallerContract 的合约,该合约使用 Constructor 合约来检索 myUint 的值。
  • 我们通过创建新的 Constructor 实例并传递参数 _myUint 来设置 myUint 的值。
  • 然后,我们可以调用 myContract.myUint() 方法来检索 myUint 变量的值。

现在,我们可以通过调用 getMyUint 函数来检索 myUint 的值。

constructor-callercontract-remix

注意

  • 合约只能有一个构造函数。
  • 在合约创建之后无法再次调用构造函数。