BitDegree Solidity课程作业:setName修改与increaseCounter实现求助
Solidity Contract Fix: setName & increaseCounter Implementation
Hey there! Let's get your FunctionTest contract sorted out with the two tasks you need to complete. I'll walk you through the fixes and explain each part clearly.
Full Updated Code
pragma solidity ^0.4.16; contract FunctionTest { bool public foo = true; string public name; uint256 public counter = 0; // Fixed setName function to accept and set the name value function setName(string _newName) public { name = _newName; } // New function to increase counter by 10 on each call function increaseCounter() public { counter += 10; } function writeToStorage() { foo = !foo; } function readFromStorageConstant() public constant returns (bool) { return foo; } function readFromStorageView() public view returns (bool) { return foo; } }
Breakdown of Changes
1. Fixing the setName Function
The original setName had no way to receive the new name value—here's what I added:
- Added a parameter
string _newNameto the function (the leading underscore is a common Solidity convention to distinguish function parameters from state variables) - Added the line
name = _newName;inside the function body, which assigns the passed value to the publicnamestate variable - Kept the
publicvisibility modifier so you can call this function from outside the contract
2. Adding the increaseCounter Function
This one's straightforward:
- Created a new
publicfunction (so it's callable externally) namedincreaseCounter - Inside the function, used the shorthand
counter += 10;to add 10 to the existingcountervalue (you could also writecounter = counter + 10;—both work the same)
Quick Notes
- Since you're using Solidity ^0.4.16, the syntax above is fully compatible with that version
- All state variables (
name,counter) are public, so you can easily read their values after calling the functions
内容的提问来源于stack exchange,提问作者GG123GG
相关产品推荐
相关产品推荐

