# Solidity 课程 7: 构造函数 **Published by:** [Novar](https://paragraph.com/@novar/) **Published on:** 2022-05-21 **URL:** https://paragraph.com/@novar/solidity-7 ## Content 构造函数(constructor)是一种特殊的函数,每个合约只能定义一个构造函数,并在部署合约的时候自动运行一次。它可以用来初始化合约的一些参数,例如初始化合约的owner地址: address owner; // 定义owner变量 // 构造函数 constructor() public { owner = msg.sender; // 在部署合约的时候,将owner设置为部署者的地址 } // 多个constructor存在,编译报错 // constructor(address _name) public{ // name = _name; // } 注意点:不能在其他合约直接修改其他合约的状态变量 如果想再修改其他合约的状态变量,必须通过合约对外暴露的函数才能修改,不能直接修改状态变量:contract TestConstructor{ address public owner; // 定义owner变量 function test() public{ Y y = new Y(msg.sender); y.name = msg.sender;//报错,不能直接修改状态变量 y.changeName(msg.sender);//可行 } } contract Y{ address public name; function changeName(address _name) public{ name = _name; } } 这节学习了合约的构造函数,和其他语言的类构造函数类似,唯一区别是,solidity的合约只能定义一个构造函数。全部代码: https://github.com/Luca-Hsu/SuperSolidity/blob/main/07_Constructor/construct.sol.txt Reference: https://mirror.xyz/ninjak.eth/X8HHTaD8hqkfshhugHHp7ho3EaLjuviya_g1l3MsF_U ## Publication Information - [Novar](https://paragraph.com/@novar/): Publication homepage - [All Posts](https://paragraph.com/@novar/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@novar): Subscribe to updates