Solidity中修改与构造函数
修改
先写两个函数
function add() external {
require(!paused,"paused");
count+=1;
}
function dele() external {
require(!paused,"paused");
count-=1;
}
可见两个函数中有都有一部分“require(!paused,"paused"); ”的重复部分,为了减少这样的重复,提高代码简洁性
则
modifier whenNotPaused()
{
require(!paused,"paused");
_;
}
使用"modifier"关键字来构造一个修改器
ps:函数中“_;”必须有。它代表这个函数的其他代码在某处运行,使用该修改器的其他代码在哪里运行
然后将修改器插入这两个代码中
modifier whenNotPaused()
{
require(!paused,"paused");
_;
}
function add() external whenNotPaused { //直接将该修改器名称放到函数性质后面
//require(!paused,"paused"); //运行到下划线这一行就会跳回函数中运行
count+=1;
}
function dele() external whenNotPaused {
count-=1;
}
构造函数
address public owner;
uint public x;
constructor(uint _x){
owner = msg.sender; //调用地址
x=_x;
}
//运行后在部署旁边会多出一个输入框,输入uint类型的数据后才可以部署
先定义变量,然后用“constructor”格式来构造。