-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation
Description
基本概念
Solidity是一种面向对象的编程语言,它支持合约之间的继承。继承允许一个合约获取另一个合约的所有非私有属性和函数,这样就可以重复使用代码,降低重复工作量。
virtual 和 override 关键字
在 Solidity 0.6.0 版本及以后,引入了 virtual 和 override 关键字用来显式控制函数和状态变量的可重写性。在实际开发中,使用 virtual 和 override 是最佳实践,以确保合约的可读性和安全性。
virtual:用于标记父合约中的函数,表示该函数可以在子合约中被重写。override:用于标记子合约中的函数,表示该函数重写了父合约中的函数。
继承的示例
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// 定义父合约
contract Parent {
string public name;
uint public age;
// 构造函数
constructor(string memory _name, uint _age) {
name = _name;
age = _age;
}
// 设置名称函数
function setName(string memory _name) public virtual {
name = _name;
}
// 设置年龄函数
function setAge(uint _age) public virtual {
age = _age;
}
}
// 定义子合约,继承自 Parent
contract Child is Parent {
string public school;
// 构造函数
constructor(string memory _name, uint _age, string memory _school) Parent(_name, _age) {
school = _school;
}
// 设置学校函数
function setSchool(string memory _school) public {
school = _school;
}
// 重载父合约的 setName 函数
function setName(string memory _name, string memory _school) public override {
name = _name;
school = _school;
}
// 调用父合约的 setAge 函数
function incrementAge() public {
setAge(age + 1);
}
// 获取所有信息
function getInfo() public view returns (string memory, uint, string memory) {
return (name, age, school);
}
}
解释
-
父合约 Parent:
setName和setAge函数使用了virtual关键字,表示这些函数可以在子合约中被重写。
-
子合约 Child:
setName函数使用了override关键字,表示它重写了父合约中的setName函数。
-
构造函数:
- 子合约的构造函数调用了父合约的构造函数,初始化
name和age,同时初始化school。
- 子合约的构造函数调用了父合约的构造函数,初始化
使用 virtual 和 override 的好处
- 明确的可重写性:使用
virtual和override明确标识哪些函数可以被重写,增加代码的可读性。 - 防止错误:防止因意外重写函数而引入的错误,确保重写操作是显式和有意的。
- 增强安全性:提高智能合约的安全性,防止意外的函数重写行为。
Metadata
Metadata
Assignees
Labels
documentationImprovements or additions to documentationImprovements or additions to documentation