solidity 合约继承

本文介绍了Solidity编程语言中如何使用`is`关键字进行合约继承,以及访问权限、函数重写和抽象合约的概念。通过示例展示了如何定义和重写`getSalary`函数,强调了在继承中子类对父类成员的访问规则,并探讨了Solidity 0.6以后版本的`abstract`、`virtual`和`override`关键字在函数定义中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

继承通过关键字 is 来实现,例如:

pragma solidity ^0.8.0;
contract Person{
  string name;
  uint age;
}
contract Man is Person{
}

访问权限

1 子类不能访问父类的private的,其他的都可以访问,比如Public internal
2 继承不允许函数或变量重名

重写函数

从 0.6 开始,solidity 引入了 abstract, virtual, override 几个关键字,用于重写函数。

pragma solidity ^0.8.0;

contract Employee {
    function getSalary() public  pure virtual returns(int){
        return 1;
    }
}

contract Manager is Employee {
    function getSalary() public  pure override returns(int){
        return 2;
    }
}

基类中可以包含没有实现代码的函数,也就是纯虚函数,那么基类必须声明为 abstract。

示例以下:

pragma solidity ^0.8.0;

abstract contract Employee {
    function getSalary() public  pure virtual returns(int);
}

contract Manager is Employee {
    function getSalary() public  pure override returns(int){
        return 2;
    }
}
### 关于Solidity智能合约编程教程 #### 学习资源概述 对于希望深入了解并掌握Solidity智能合约开发的学习者来说,存在多种途径获取高质量的学习材料。官方文档提供了详尽的基础概念介绍和技术细节说明[^1]。 #### 编写指南要点 编写Solidity智能合约时需注意几个核心方面: - **语言特性**:作为一种面向对象的语言,Solidity支持类、继承等现代编程范式;同时具备特定的数据类型如`address`用于处理账户地址[^4]。 - **安全实践**:鉴于区块链环境的独特性,在编码过程中应特别关注安全性考量,比如防止重入攻击等问题的发生[^3]。 - **测试框架集成**:利用Truffle Suite这样的工具集可以极大地方便开发者进行本地调试与单元测试工作。 #### 实例展示——简易投票系统 下面给出一段简单的Solidity代码片段作为示例,该程序实现了基本的在线投票功能: ```solidity // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Voting { struct Proposal { bytes32 name; uint voteCount; } address public chairperson; mapping(address => bool) public voters; Proposal[] public proposals; modifier onlyChairperson() { require(msg.sender == chairperson, "Not the chairperson"); _; } constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; for (uint i = 0; i < proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } function giveRightToVote(address voter) external onlyChairperson { require(!voters[voter], "Already voted."); voters[voter] = true; } function vote(uint proposal) external { require(voters[msg.sender], "No voting rights."); proposals[proposal].voteCount += 1; } function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } } } ``` 此段代码定义了一个名为Voting的合约,允许创建提案列表,并由指定负责人授予选民资格后参与投票过程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李卓书

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值