在Solidity版本0.5.2中,如何在另一个容器中调用合同?

时间:2019-01-23 05:03:49

标签: blockchain ethereum solidity smartcontracts remix

我使用的是Solidity版本0.5.2

pragma solidity ^0.5.2;

contract CampaignFactory{
address[] public deployedCampaigns;

function createCampaign(uint minimum) public{
    address newCampaign  = new Campaign(minimum,msg.sender);  //Error 
//here!!!
    deployedCampaigns.push(newCampaign);
} 

function getDeployedCampaigns() public view returns(address[] memory){
    return deployedCampaigns;
}
}

在CampaignFactory合同内分配调用Campaign合同时出现错误

TypeError: Type contract Campaign is not implicitly convertible to expected 
type address.        
address newCampaign  = new Campaign(minimum,msg.sender);

我还有另一个称为Campaign的合同,我想在CampaignFactory中访问。

contract Campaign{
//some variable declarations and some codes here......

我的构造函数如下

constructor (uint minimum,address creator) public{
    manager=creator;
    minimumContribution=minimum;

}

2 个答案:

答案 0 :(得分:1)

您可以投放它:

address newCampaign = address(new Campaign(minimum,msg.sender));

或者更好的是,停止使用address并使用更具体的类型Campaign

pragma solidity ^0.5.2;

contract CampaignFactory{
    Campaign[] public deployedCampaigns;

    function createCampaign(uint minimum) public {
        Campaign newCampaign = new Campaign(minimum, msg.sender);
        deployedCampaigns.push(newCampaign);
    } 

    function getDeployedCampaigns() public view returns(Campaign[] memory) {
        return deployedCampaigns;
    }
}

答案 1 :(得分:0)

要从另一个合同中调用现有合同,请在演员表中传递合同地址

pragma solidity ^0.5.1;

contract D {
    uint x;
    constructor (uint a) public  {
        x = a;
    }
    function getX() public view returns(uint a)
    {
        return x;
    }
}

contract C {
//DAddress : is the exsiting contract instance address after deployment
    function getValue(address DAddress) public view returns(uint a){
        D d =D(DAddress);
        a=d.getX();
    }
}