在特弗斯的宠物店教程里。Adoption.sol是--
pragma solidity ^0.4.19;
contract Adoption {
address[16] public adopters;
// Adopting a pet
function adopt(uint petId) public returns (uint) {
require(petId >= 0 && petId <= 15);
adopters[petId] = msg.sender;
return petId;
}
}TestAdoption.sol是--
pragma solidity ^0.4.19;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Adoption.sol";
contract TestAdoption {
Adoption adoption = Adoption(DeployedAddresses.Adoption());
// Testing retrieval of a single pet's owner
function testGetAdopterAddressByPetId() public {
// Expected owner is this contract
address expected = this;
address adopter = adoption.adopters(8);
Assert.equal(adopter, expected, "Owner of pet ID 8.");
}
}我的问题是address adopter = adoption.adopters(8); in TestAdoption.sol,我认为adoption.adopters是一个数组,它的元素应该通过[8]而不是(8)访问。
然而,马弗斯的代码是正确的。实际上,将(8)更改为[8]将导致可靠的编译错误--
TypeError: Indexed expression has to be a type, mapping or array (is function (uint256) view external returns (address))
address adopter = adoption.adopters[8];
^---------------^背后的理论是什么?
发布于 2018-02-21 15:34:39
无法从另一份合同直接访问这些字段。address[16] public adopters中的public关键字将生成一个名称相同的getter函数,因此是adoption.adopters(8)。
https://ethereum.stackexchange.com/questions/40433
复制相似问题