solidity合约单继承
我们声明一个合约Bob,让它继承Person合约,看看有哪些属性和方法能继承到子合约。
// SPDX-License-Identifier: MIT
pragma solidity ^0.4.0;
contract Person{
string _name;
uint internal _age;
uint private _height;
uint public _weight;
function test() constant returns (string) {
return _name;
}
function test1() constant public returns (uint) {
return _height;
}
function test2() constant private returns (uint) {
return _weight;
}
function test3() constant internal returns (uint) {
return _age;
}
}
contract Bob is Person { // 合约Bob继承自Proson合约
}
为什么能看见_weight函数?
public属性的_weight属性会自动生成一个和属性名一样的get(就是读取)函数。
为什么能看见test和test1函数?
test()和test1()是public类型。
所有,只有public类型的函数能继承到子合约中。
哪些类型的属性可以继承到Bob子合约?)
测试:
总结:
-
子合约可以继承public和internal类型的属性
扫描二维码关注公众号,回复: 15274593 查看本文章 -
子合约只能继承public类型的函数
合约多继承
// SPDX-License-Identifier: MIT
pragma solidity ^0.4.0;
contract Person{
string _name;
uint internal _age;
uint private _height;
uint public _weight;
// 读取_name
function test() constant returns (string) {
return _name;
}
function test1() constant public returns (uint) {
return _height;
}
function test2() constant private returns (uint) {
return _weight;
}
function test3() constant internal returns (uint) {
return _age;
}
}
contract Person1 {
string _sex;
// 构造函数
function Person1() {
_sex = "male";
}
// get方法读取_sex
function sex() constant returns (string) {
return _sex;
}
}
contract Bob is Person, Person1 { // 合约Bob继承自Proson和Person1合约
function testName() constant returns (string) {
return _name;
}
function testAge() constant returns (uint) {
return _age;
}
function testWeight() constant returns (uint) {
return _weight;
}
}
有sex函数,说明可以多继承。