Solidity函数重写报Expected '{' but got 'override'编译错误
Solidity函数重写编译报错
ParserError: Expected '{' but got reserved keyword 'override'解决方法 报错触发原因
- 版本范围设置错误:
override是Solidity 0.6.0版本才正式引入的关键字,原代码声明的编译版本范围为>=0.4.16 <0.9.0,当编译器使用0.4.x、0.5.x版本解析代码时,无法识别override关键字,直接抛出语法解析错误。 - 重写语法不符合规范:0.6.0及以上版本的Solidity要求,父合约中允许被子合约重写的函数必须显式添加
virtual修饰符,子合约重写对应函数时才能使用override关键字。原代码父合约的check()函数未添加virtual,即使版本符合要求也会抛出重写权限错误。 - 语法细节错误:源文件第一行的SPDX许可证声明缺少注释前缀
//,会被编译器识别为无效语句。
原问题复现代码
SPDX-License-Identifier: MIT pragma solidity >=0.4.16 <0.9.0; contract parent{ string public str = "Black"; function check() public view returns(string memory){ return str; } } contract child is parent { string public st = "Box"; function check() public view override returns(string memory){ return string(abi.encodePacked(str,st)); } }
修复后可正常编译的代码
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Parent{ string public str = "Black"; function check() public view virtual returns(string memory){ return str; } } contract Child is Parent { string public st = "Box"; function check() public view override returns(string memory){ return string(abi.encodePacked(str,st)); } }
修复点说明
- 将编译版本固定为0.6.0以上的稳定版本(示例采用生态最常用的0.8.x系列),确保编译器可正常识别
virtual、override关键字 - 为父合约中需要被重写的
check()函数添加virtual修饰符,显式声明该函数开放重写权限 - 补全SPDX许可证声明前的
//注释前缀,符合Solidity源文件语法要求
内容的提问来源于stack exchange,提问作者Thermal Ice
相关产品推荐
相关产品推荐

