pragma solidity >=0.8.0;
contract Voting {
//该合约一开始启动的时候,就把所有候选人定死
// ↓表示private
string[] internal nameList;
// ↓ 在github的solidity->typecheck源码中看到的
constructor(string[] memory names) {//waring:构造函数输入的参数只能是memory(值类型)不能是storage(引用类型)
nameList=names;
}
//比较两个字符串是否相等
function compare(string memory a, string memory b) pure internal returns (bool) {
if (bytes(a).length != bytes(b).length) {
return false;
}
for (uint i = 0; i < bytes(a).length; i ++) {
if(bytes(a)[i] != bytes(b)[i]) {
return false;
}
}
return true;
}
//字典 unsigned Int, 记住字典如果key是string,那么key是不能填变量的
mapping(uint=>uint) internal votesReceived;
//返回该用户的下标
function num(string memory name) view internal returns(uint){
for(uint i = 0; i< nameList.length; i++){
if(compare(name,nameList[i])) return i;
}
return 9999;
}
//该人票数+1
function vote(string memory name) public{
uint index=num(name);
require(index!=9999);//需要里面的满足才能继续 //异常处理,相当于 if(里面的为false) return
votesReceived[index]+=1;
}
//查看该人的票
function totalVotesFor(string memory name) view public returns(uint){
uint index=num(name);
require(index!=9999);
return votesReceived[index];
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)