Solidity开发指南(七):语法解析

Solidity开发指南(七):语法解析

96 米饭超人 595a1b60 08f6 4beb 998f 2bf55e230555 关注

2018.06.01 10:26 字数 468 阅读 90评论 0喜欢 1

1、 solidity 类的多继承、重写

solidity 类具有多继承的特性:

pragma solidity ^0.4.19

contract Animal1 { 

    uint age;

}

contract Animal2 { 

    string weight;

}

contract Dog is Animal1, Animal2 { 

    // Dog 会继承 Animal1 及 Animal2 两个类

}

重写 与其他语言相通,即子类的同名函数会覆盖从父类继承的方法:

pragma solidity ^ 0.4 .19;

contract Animal {  
    function testFunc() public pure returns(string) {
        return "Animal testFunc";
    }
}

// 子类重写了从父类继承过来的方法,会以子类的方法为基准

contract Dog is Animal {  
    function testFunc() public pure returns(string) {
        return "Dog testFunc";
    }
}

2、 solidity 函数的访问权限

solidity 函数分为四种访问权限:

private : 私有函数。内部正常访问,外部无法访问,子类无法继承。
internal : 内部函数。内部正常访问,外部无法访问,子类可继承。
public : 公共函数。内部正常访问,外部正常访问,子类可继承。
external : 外部函数。内部不能访问,外部正常访问,子类可继承。

pragma solidity ^0.4.19;

contract Animal {  
    // public  公有:外部、内部、子类都可使用
    function testPublic() public pure returns (string) {
        return "public";
    }
    // private 私有:合约内部可以正常访问
    function testPrivate() private pure returns (string) {
        return "private";
    }
    // internal 内部:合约内部可以正常访问
    function testInternal() internal pure returns (string) {
        return "internal";
    }
    // external 外部:只能供外部访问
    function testExternal() external pure returns (string) {
        return "external";
    }
    // 未做任何修改时,使用pure
    function f() public pure {
        testPublic();
        testInternal();
        testPrivate();
        //testExternal(); // 报错,只能供外部访问
    }
}

contract Dog is Animal {  
    // 继承 public、internal、external 类型的函数
}

// Dog.testPublic() 继承,可用
// Dog.testInternal() 继承,不可用(internal函数外部无法访问)
// Dog.testExternal() 继承,可用
// Dog.f() 继承,可用

3、 solidity 函数中 pure 、 view 、 constant 的区别

solidity 函数的完整声明格式为:

function 函数名(参数)  public|private|internal|external  pure|view|constant  无返回值|returns (返回值类型)  

比如:

pragma solidity ^0.4.19;

contract Animal {  
    string homeAddress = "北京市";
    uint weight;

    // pure
    function getAge() public pure returns (uint) {
        return 30;
    }

    // view
    function getCurrentAddress() public view returns (address) {
        return msg.sender;
    }

    // view
    function getHomeAddress() public view returns (string) {
        return homeAddress;
    }

    function setWeight(uint w) public {
        weight = w;
    }

    // constant/view都行
    function getWeight() public constant returns (uint) {
        weight = 200;
        return weight;
    }
}

结论如下:

只有当函数有返回值的情况下,才需要使用 pure 、 view 、 constant
pure : 当函数返回值为自变量而非变量时,使用 pure
view : 当函数返回值为全局变量或属性时,使用 view
constant : 可以理解为 view 的旧版本,与 view 是等价的
如果一个函数有返回值,函数中正常来讲需要有 pure 、 view 或 constant 关键字,如果没有,在调用函数的过程中,需要主动去调用底层的call方法。

注: 如果一个函数中带了关键字 view 或 constant ,就不能修改状态变量的值。但凡是是带了这两个关键字,区块链就默认只是向区块链读取数据,读取数据不需要花gas,但是不花gas就不可能修改状态变量的值。写入数据或者是修改状态变量的值都需要花费gas。

猜你喜欢

转载自blog.csdn.net/jfkidear/article/details/89205537