solidity智能合约[36]-连续继承与多重继承

连续继承

合约可以被连续的继承,在下面的合约中,father继承了grandfather、son继承了father。那么son也同样继承了grandfather中的状态变量和方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
contract grandfather{
uint public money=10000;
function dahan() public pure returns(string){
return "dahan";
}
}

contract father is grandfather{

}
contract son is father{

}

连续继承重名问题

下面的合约中,grandfather合约与 father合约中状态变量的名字、函数的名字都是相同的,这时,son中的状态变量money和继承的函数 以父类father合约中的状态变量和函数为准。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pragma solidity ^0.4.23;


contract grandfather{
uint public money=10000;
function dahan() public pure returns(string){
return "dahan";
}
}

contract father is grandfather{
uint public money=9999;
function dahan() public pure returns(string){
return "alice";
}
}

contract son is father{
function getMonry() returns(uint){
return money;
}
}

多重继承

合约可以继承多个合约,也可以被多个合约继承。如下所示:

1
2
3
4
5
6
7
8
9
10
contract father{
}


contract mother{
}

contract son is father,mother{

}

多重继承有重名

多重继承有重名时,继承的顺序时很重要的,以最后继承的为主。例如下面的例子中,son合约最后继承了mother,因此以mother合约中的money=8888为准。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
contract father is grandfather{
uint public money=9999;

function dahan() public pure returns(string){
return "alice";
}
}


contract mother{
uint public money=8888;
uint public weight=100;

}

contract son is father,mother{

}