반응형
두 개 이상의 스마트 컨트랙의 상속을 받았을 때 어떤 식으로 구현하는지에 대해 학습한다.
Father, Mother, Son 스마트 컨트랙이 존재한다.
Son 스마트 컨트랙이 Father과 Mother의 스마트 컨트랙을 상속받는 것을 구현한다.
Father과 Mother의 스마트 컨트랙에 기능을 똑같이 적용한다.
이 두 스마트 컨트랙을 Son 스마트 컨트랙에 상속시킨다.
위와 같이 간단하게 상속을 시킬 수 있는데 오류가 발생한다.
이 오류는 getMoney가 Mother과 Father에 똑같은 이름으로 존재하기 때문에 발생한다.
따라서 오버라이딩을 해야 한다.
두 개 이상의 스마트 컨트랙을 상속받을 때, 두 개 스마트 컨트랙의 함수가 같을 때 상속받는 스마트 컨트랙에서 오버라이딩을 해야 한다.
// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;
contract Father{
uint256 public fatherMoney = 100;
function getFatherName() public pure returns(string memory){
return "KimJung";
}
function getMoney() public view virtual returns(uint256){
return fatherMoney;
}
}
contract Mother{
uint256 public motherMoney = 500;
function getMotherName() public pure returns(string memory){
return "Leesol";
}
function getMoney() public view virtual returns(uint256){
return motherMoney;
}
}
contract Son is Father, Mother {
function getMoney() public view override(Father,Mother) returns(uint256){
return fatherMoney+motherMoney;
}
}
Mother과 Father에 virtual을 작성하고 Son에 override를 작성한다.
이때 override에 Mother과 Father 스마트 컨트랙을 써야 한다.
Son을 배포하고 결과를 확인한다.
getMoney를 누르면 600이 나오는 것을 확인할 수 있다.
Father에서 100을 받고 Mother에서 500을 받았기 때문에 600이 출력되는 것이다.
반응형
'PBL > 솔리디티' 카테고리의 다른 글
event2 - indexed (0) | 2024.06.04 |
---|---|
event1- 정의 (0) | 2024.06.04 |
상속2 - overriding 오버라이딩 (0) | 2024.05.28 |
상속1 - 정의 (0) | 2024.05.22 |
instance2 - constructor (0) | 2024.05.22 |