Solidity:构造函数需要总是 "public"?

Solidity: Constructor function needs to be always "public"?

在 solidity 中,虽然将“withdraw”函数关联为只能从管理合约中调用,但“construct”会派上用场。

address public owner;
constructor() public { owner =msg.sender;}

问:为什么一定要设置为“public”函数?因为我们不希望只有我们自己触发提款,所以不应该将其输入为“内部”或“私人”吗?

提款功能应标记为 public 或外部供您或其 non-contract 所有者使用,以便能够提款。为什么?如果将函数标记为私有,则只有智能合约内部的函数才能与之交互,并且通过将函数标记为内部函数,合约内部的函数和继承自该函数的合约将能够调用该函数。为什么你可能想这样做?因为作为普通用户,您将无法直接调用此函数。因此,通过将此函数设置为 public 或外部函数,每个用户都可以与该函数进行交互。这是你的问题。

How come it has to be set as a "public" function? As we want no one but us to trigger the withdraw, shouldn´t it be entered as "internal" or "private"?

您可以将函数设置为 public 并创建一个 require 语句(它可以是修饰符或条件“if”,如您所愿。)并仅检查汇款人是否为所有者。并且只有在是的情况下,才退出。这是一个例子:

function withdraw() public {
    require(msg.sender == owner, "Only the owner can call this function.");

    // Withdraw logic here.
}

希望你觉得这有用:)

构造函数只是在部署时触发,因此在部署之前没有其他人可以调用它,它可以是 public 你不会有任何问题,但在最新的 solidity 版本中没有必要标记构造函数作为 public