반응형
super는 함수를 오버라이딩할 때 사용하며, 원래의 함수를 가져오는 역할을 한다.
// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;
contract Father {
event FatherName(string name);
function who() public virtual{
emit FatherName("KimDaeho");
}
}
contract Son is Father{
event sonName(string name);
function who() public override {
super.who();
emit sonName("KimJin");
}
}
여러 번 출력을 위해 emit FatherName("KimDaeho");를 여러 번 입력할 필요 없이 super를 사용된다.
위와 같이 super를 사용하면 father name을 자체로 갖고 오는 것을 알 수 있다.
컴파일을 하고 son을 배포하면 두 개의 이벤트가 출력된 것을 확인할 수 있다.
상속의 순서를 통해 super가 어떻게 작동하는지 알아본다.
// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;
contract Father {
event FatherName(string name);
function who() public virtual{
emit FatherName("KimDaeho");
}
}
contract Mother {
event MotherName(string name);
function who() public virtual{
emit MotherName("leeSol");
}
}
contract Son is Father, Mother{
function who() public override(Father,Mother){
super.who();
}
}
Father와 Mother를 상속받는 Son이 존재한다.
Father와 Mother에는 who라는 함수가 있고 이 who를 Son은 오버라이딩한다.
오버라이딩한 형태에서 super를 통해 who를 있는 그대로 가져온다.
Son을 배포하고 살펴보면 Mother의 who를 가져오는 것을 알 수 있다.
Father와 Mother에 둘 다 who 함수가 존재하지만 Mother의 who를 가져온 이유는 Mother의 스마트 컨트랙이 최신이기 때문이다.
// SPDX-License-Identifier:GPL-30
pragma solidity >= 0.7.0 < 0.9.0;
contract Father {
event FatherName(string name);
function who() public virtual{
emit FatherName("KimDaeho");
}
}
contract Mother {
event MotherName(string name);
function who() public virtual{
emit MotherName("leeSol");
}
}
contract Son is Mother, Father{
function who() public override(Father,Mother){
super.who();
}
}
반대로 Father와 Mother의 순서를 바꿔서 배포를 진행하면
Father name 이벤트가 출력된 것을 알 수 있다.
상속의 순서는 맨 오른쪽 최신의 것이 super를 통하여 상속되는 것이다.
즉, 최신의 것이 옛날 것을 덮는다고 생각하면 된다.
반응형
'PBL > 솔리디티' 카테고리의 다른 글
event2 - indexed (0) | 2024.06.04 |
---|---|
event1- 정의 (0) | 2024.06.04 |
상속3 - 두개 이상 상속하기 (0) | 2024.05.28 |
상속2 - overriding 오버라이딩 (0) | 2024.05.28 |
상속1 - 정의 (0) | 2024.05.22 |