
2

solidity | 关键词 virtual、override、super
source link: https://benpaodewoniu.github.io/2023/02/19/solidity59/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

solidity | 关键词 virtual、override、super
virtual
和 override
相当于重写父类的方法,作用和 java
的一样。
virtual
- 父合约中的函数,如果希望子合约重写,需要加上
virtual
关键字。
- 父合约中的函数,如果希望子合约重写,需要加上
override
- 子合约重写了父合约中的函数,需要加上
override
关键字。
- 子合约重写了父合约中的函数,需要加上
注意:用 override
修饰 public
变量,会重写与变量同名的 getter
函数,例如:
mapping(address => uint256) public override balanceOf;
pragma solidity ^0.8.0;
contract A{
string public name;
string public t;
uint256 public c;
function test() public{
pre();
c = c + 1;
}
function pre() internal virtual{
t = "test";
}
}
contract Test is A {
function pre() internal override{
name = "test";
}
}
部署 Test
合约,部署完成,调用变量
C
0
name
""
t
""
调用 test
函数,这几个值变为
C
1
name
test
t
""
说明,重写方法后,父函数就不再执行。如果想要执行父方法,可以使用 super
。
pragma solidity ^0.8.0;
contract A{
string public name;
string public t;
uint256 public c;
function test() public{
pre();
c = c + 1;
}
function pre() internal virtual{
t = "test";
}
}
contract Test is A {
function pre() internal override{
super.pre();
name = "test";
}
}
请我喝杯咖啡吧~
</article
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK