为什么我的智能合约构造函数在部署时没有自动调用?

Why is my smart contract constructor not called automatically when it is deployed?

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

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

pragma solidity ^0.4.17;

contract Lottery {
    address public manager;

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

您的构造函数应该会自动调用。

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

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

Solidity 0.4.22 更改为使用 constructor 而不是合约名称以避免这些类型的错误:

https://github.com/ethereum/solidity/releases/tag/v0.4.22
Constructors should now be defined using constructor(uint arg1, uint arg2) { ... } to make them stand out and avoid bugs when contracts are renamed but not their constructors.

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