Доступ к объекту структуры одного контракта из другого

У меня 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
}

Я не хочу наследовать контракт. Я хочу получить доступ к объекту структуры studentконтракта Studentиз контракта ClassRoom. Как это сделать?

Ответы (1)

В конструкторе для Student сопоставление studentNames и uint ID не инициализируется. Если вы попытаетесь сделать 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;
    }
}

Вы можете получить доступ к сопоставлению извне контракта, если объявите его общедоступным, как указано выше. Обратите внимание, что это дает доступ только для чтения. Вам по-прежнему понадобится функция в контракте Student для обновления члена 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);
    }
}
Я пробовал вышеуказанный контракт и получил ошибку: Untitled2:30:16: Ошибка: возвращаемый тип аргумента кортежа (недоступный динамический тип, uint256, bool) не может быть неявно преобразован в кортеж ожидаемого типа (строковая память, uint256, bool). вернуть student.StudentNames (ID);
@comeback4you, возвращающий кортежи из типа структуры, несовместим со строковым типом. Попробуйте вместо этого использовать bytes32.