Solidity

如何從子合約呼叫父合約中的函式?

  • January 24, 2021

我是新手。請耐心等待我的愚蠢問題

我想從它的孩子那裡獲得父契約中名為 num 的變數。

所以,我的想法是先嘗試獲取父合約的地址,然後我將生成實例以獲取父合約中的num。

pragma solidity ^0.6.0;

contract parent{  
   uint public num;  
   function setValue(uint _value) public{  
       num= _value;  
   }  
   function getValue() public view returns(uint){  
       return num;  
   }  
}  
contract child is parent{    
   function get_address() public view returns(address){  
       return address(parent);  // here I have got an error... 
   }  
}  

你們能給我一些建議嗎?

我對解釋感到困惑,但我相信你想要實現的是parentchild契約中讀取和更新契約的狀態。以下是如何實現它:

pragma solidity ^0.6.0;

contract parent {  
   uint public num;
   
   function setValue(uint _value) public {  
       num = _value;  
   }
   
   function getValue() public view returns(uint) {  
       return num;  
   }  
}


contract child {
   parent parentInstance;
   constructor(address _parent_address) public {
       parentInstance = parent(_parent_address);
   }
   
   function getParentValue() public view returns(uint){  
       return parentInstance.getValue();
   }  
   
   function setParentValue(uint _child_value) public {
       parentInstance.setValue(_child_value);
   }  
}

我的範例中的不同之處在於,我在child契約中創建了契約實例,parent現在您可以參考parent契約狀態。這是通過在parent合約的建構子中傳遞合約的地址來實現的child

附加邏輯,如何將地址自動傳遞給子合約:

pragma solidity ^0.6.0;

contract parent {
   child public childContract;
   uint public num;
   
   constructor() public {
       childContract = new child(address(this));
   }
   
   function setValue(uint _value) public {  
       num = _value;  
   }
   
   function getValue() public view returns(uint) {  
       return num;  
   }  
}


contract child {
   parent parentInstance;
   constructor(address _parent_address) public {
       parentInstance = parent(_parent_address);
   }
   
   function getParentValue() public view returns(uint){  
       return parentInstance.getValue();
   }  
   
   function setParentValue(uint _child_value) public {
       parentInstance.setValue(_child_value);
   }  
}

引用自:https://ethereum.stackexchange.com/questions/92685