You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solidity合约编译报错:ParserError: Expected '{' but got 'constant'

Solidity编译错误修复方案

错误原因

你使用的Solidity 0.8.17版本不兼容代码里的旧语法,具体问题如下:

  1. constant修饰函数的写法在Solidity 0.5+版本已被废弃,读取状态变量的函数需用view关键字
  2. 旧版本中与合约同名的构造函数写法,在0.5+版本已被constructor关键字替代
  3. 返回字符串类型时,必须指定内存位置memory,否则会触发语法错误

修正后的代码

pragma solidity ^0.8.17;
contract Greeter {
    string greeting;
    
    // 用constructor关键字定义构造函数
    constructor(string memory _greeting) public {
        greeting = _greeting;
    }
    
    // 用view替代constant,返回值指定memory
    function greet() public view returns (string memory) {
        return greeting;
    }
}

关键修改说明

  • 替换构造函数写法:将与合约同名的Greeter函数改为constructor,这是Solidity 0.5+版本的标准构造函数定义方式
  • 替换函数修饰符:constant改为view,view专门用于标记仅读取合约状态、不修改状态的函数
  • 补充返回值存储位置:string改为string memory,字符串属于引用类型,必须明确指定存储位置(此处用memory表示临时存储在内存中)

内容的提问来源于stack exchange,提问作者Tanzeel ur Rehman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:45:33