Доступ к структурному объекту одного контракта из другого
У меня есть 2 контракта:
contract Student{
uint ID;
struct stu{
string name;
uint age;
bool tookTest;
}
mapping(uint => stu) StudentNames;
function Student(string _name,uint _age) {
//ID is incremented
stu s = StudentNames[ID];
s.name = _name;
s.age = _age;
s.tookTest = false;
}
}
contract ClassRoom {
address studentAddr;
Student student;
function ClassRoom(address addr) {
studentAddr = addr;
student = Student(addr);
}
//some function that performs a check on student obj and updates the tookTest status to true
}
Я не хочу наследовать какой-либо контракт. Я хочу получить доступ к объекту struct student
контракта Student
from contract ClassRoom
. Как это сделать?
1 ответ
4
В конструкторе для Student имя студента-студента и идентификатор uint не инициализируются. Если вы попытаетесь сделать stu s = studentNames[ID]
, вы получите 0.
Вы хотите что-то вроде следующего:
contract Student{
struct stu{
string name;
uint age;
bool tookTest;
}
mapping(uint => stu) public studentNames;
function addStudent (uint ID, string _name, uint _age) {
studentNames[ID] = stu(_name, _age, false);
}
function updateStudent (uint ID) {
studentNames[ID].tookTest = true;
}
}
Вы можете получить доступ к сопоставлению вне договора, если объявите его общедоступным, как указано выше. Обратите внимание, что это дает только доступ READ. Вам все равно потребуется функция в контракте Студента, чтобы обновить член takeTest.
например.
contract ClassRoom {
address studentAddr;
Student student;
function ClassRoom(address addr) {
studentAddr = addr;
student = Student(addr);
}
//some function that performs a check on student obj and updates the tookTest status to true
function updateTookTest (uint ID) {
student.updateStudent(ID);
}
//if you want to access the public mapping
function readStudentStruct (uint ID) constant returns (string, uint, bool) {
return student.studentNames(ID);
}
}
ответил bozzle 23 AM00000080000004231 2016, 08:02:42