【问题标题】:Why is my smart contract constructor not called automatically when it is deployed?为什么我的智能合约构造函数在部署时没有自动调用?
【发布时间】:2019-12-11 17:50:32
【问题描述】:

当我部署以下智能合约时,变量管理器的地址为 0x0000000000000000000000000000000000000000。只有在我调用构造函数 (Lottery()) 之后,变量管理器才具有与部署它的帐户匹配的地址。

为什么我的构造函数没有被自动调用?

pragma solidity ^0.4.17;

contract Lottery {
    address public manager;

    function Lottery() public {
        manager = msg.sender;
    }
}

【问题讨论】:

    标签: ethereum solidity smartcontracts


    【解决方案1】:

    你的构造函数应该被自动调用。

    我使用 Remix (https://remix.ethereum.org) 和编译器版本 0.4.17,然后按预期进行部署,并将管理器设置为部署地址。

    如果合约名称和构造函数名称不同,就会出现您遇到的问题,因此函数不再是构造函数。

    Solidity 0.4.22 更改为使用 constructor 代替合约名称以避免此类错误:

    https://github.com/ethereum/solidity/releases/tag/v0.4.22
    现在应该使用 constructor(uint arg1, uint arg2) { ... } 来定义构造函数,以使它们脱颖而出并避免在重命名合约而不是它们的构造函数时出现错误。

    我建议您考虑使用更高版本的 Solidity 0.5.x。

    【讨论】:

    • OP 可以在 Remix 上尝试 0.4.25.0。这是较早的稳定版本之一,可能更适合您已经编写的内容。
    猜你喜欢
    • 2020-11-14
    • 1970-01-01
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    • 2018-09-23
    相关资源
    最近更新 更多