Solidify实现一个智能合约3(单继承与多继承)

单继承

方法/函数的继承

代码示例

pragma solidity ^0.4.4;

contract Animal {

  uint  _weight;
  uint private _height;
  uint internal _age;
  uint public _money;

  function test1() constant returns (uint) {
    return _weight;
  }
  function test2() constant public returns (uint) {
    return _height;
  }
  function test3() constant internal returns (uint) {
    return _age;
  }
  function test4() constant private returns (uint) {
    return _money;
  }
}

//Dog继承Animal,is表示继承
contract Dog is Animal {
  
}

效果如下:

Solidify实现一个智能合约3(单继承与多继承)_第1张图片

说明:继承中,函数(方法)的权限为public时才能被子合约继承。

属性继承

代码示例

pragma solidity ^0.4.4;

contract Animal {

  uint  _weight;
  uint private _height;
  uint internal _age;
  uint public _money;

  function test1() constant returns (uint) {
    return _weight;
  }
  function test2() constant public returns (uint) {
    return _height;
  }
  function test3() constant internal returns (uint) {
    return _age;
  }
  function test4() constant private returns (uint) {
    return _money;
  }
}

//Dog继承Animal,is表示继承
contract Dog is Animal {

  function testWeight() constant returns (uint) {
    return _weight;
  }
  //private属性不能被继承
  /*
  function testHeight() constant returns (uint) {
    return _height; 
  }*/
  function testAge() constant returns (uint) {
    return _age;
  }
  function testMoney() constant returns (uint) {
    return _money;
  }
}

效果如下

Solidify实现一个智能合约3(单继承与多继承)_第2张图片

说明:子合约可以继承public和internal类型的属性,不能继承private类型的属性。

多继承

代码示例

pragma solidity ^0.4.4;

contract Animal {

  uint  _weight;
  uint private _height;
  uint internal _age;
  uint public _money;

  function test1() constant returns (uint) {
    return _weight;
  }
  function test2() constant public returns (uint) {
    return _height;
  }
  function test3() constant internal returns (uint) {
    return _age;
  }
  function test4() constant private returns (uint) {
    return _money;
  }
}

contract Sex {
  uint _sex;
  function Sex() {
    _sex = 1;
  }
  function sex() constant returns (uint) {
    return _sex;
  }
}

//Dog继承Animal和Sex,is表示继承,多继承用","分开。
contract Dog is Animal,Sex {

  function testWeight() constant returns (uint) {
    return _weight;
  }
  //private属性不能被继承
  /*
  function testHeight() constant returns (uint) {
    return _height; 
  }*/
  function testAge() constant returns (uint) {
    return _age;
  }
  function testMoney() constant returns (uint) {
    return _money;
  }
}

效果如下:

Solidify实现一个智能合约3(单继承与多继承)_第3张图片

说明:效果同上,继承时,子合约的优先级高。

 

你可能感兴趣的:(区块链智能合约)