Solidity合约编译错误:未声明标识符_studentLastName求解
解决Solidity中
_studentLastName未声明的编译错误 错误根源
addStudentDetails函数定义时只接收了_studentFirstName参数,但函数内部却直接使用_studentLastName给结构体赋值,编译器找不到该变量的声明,触发Undeclared identifier错误- 同时
emit studentAdded时多传了msg.value参数,和事件studentAdded的定义(三个参数)不匹配,也会导致编译失败
修复操作
- 给
addStudentDetails函数补充string memory _studentLastName参数,让函数能接收姓氏数据 - 修正
emit studentAdded的调用,移除多余的msg.value,保证参数数量和事件定义一致
修复后的完整代码
// SPDX-License-Identifier: MIT pragma solidity >= 0.4.0 <0.9.0; contract Scorecard{ uint256 studentCount = 0; address public classTeacher; constructor() public { classTeacher = msg.sender; } modifier onlyClassTeacher(address _classTeacher) { require(classTeacher == _classTeacher, "Only the class teacher has access to this function"); _; } struct StudentDetails{ string studentFirstName; string studentLastName; uint256 id; } struct Score{ uint256 studentId; uint256 englishMarks; uint256 mathMarks; uint256 scienceMarks; } mapping(uint => StudentDetails) students; mapping(uint => Score) scores; event studentAdded(string _studentFirstName, string _studentLastName, uint256 _studentId); event studentScoresRecorded(uint256 _studentId, uint256 _englishMarks, uint256 _mathMarks, uint256 _scienceMarks); function addStudentDetails (string memory _studentFirstName, string memory _studentLastName) public onlyClassTeacher(msg.sender){ StudentDetails storage studentObj = students[studentCount]; studentObj.studentFirstName = _studentFirstName; studentObj.studentLastName = _studentLastName; studentObj.id = studentCount; emit studentAdded(_studentFirstName, _studentLastName, studentCount); studentCount++; } function addStudentScores(uint256 _studentId, uint256 _englishMarks, uint256 _mathMarks, uint256 _scienceMarks ) public onlyClassTeacher(msg.sender){ Score storage scoreObject = scores[_studentId]; scoreObject.englishMarks = _englishMarks; scoreObject.mathMarks = _mathMarks; scoreObject.scienceMarks = _scienceMarks; scoreObject.studentId = _studentId; emit studentScoresRecorded(_studentId, _englishMarks, _mathMarks, _scienceMarks); } }
内容的提问来源于stack exchange,提问作者Shawngilbert107
相关产品推荐
相关产品推荐

