상세 컨텐츠

본문 제목

Solidity - Inheritance

Programming Language/Solidity

by Yongari 2022. 12. 30. 22:09

본문

 

 

Inheritance
상속

Solidity supports multiple inheritance. Contracts can inherit other contract by using the is keyword.
솔리디티는  다중 상속을 지원합니다. 계약은 is 키워드를 사용하여 다른 계약을 상속할 수 있습니다.

Function that is going to be overridden by a child contract must be declared as
 virtual.
자식 계약에 의해 override 기능은 가상으로 선언되어야 합니다.

Function that is going to override a parent function must use the keyword override.
부모계약을 override할 함수는 키워드 override를 사용해야합니다.

Order of inheritance is important.
상속의 순서는 중요하다.


You have to list the parent contracts in the order from “most base-like” to “most derived”.

당신은 "가장 기본적인"에서 "가장 파생적인" 순서로 상위 계약을 나열해야 합니다.

 

 

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/* Graph of inheritance
    A
   / \
  B   C
 / \ /
F  D,E

*/

contract A {
    function foo() public pure virtual returns (string memory) {
        return "A";
    }
}

// Contracts inherit other contracts by using the keyword 'is'.
contract B is A {
    // Override A.foo()
    function foo() public pure virtual override returns (string memory) {
        return "B";
    }
}

contract C is A {
    // Override A.foo()
    function foo() public pure virtual override returns (string memory) {
        return "C";
    }
}

// Contracts can inherit from multiple parent contracts.
// When a function is called that is defined multiple times in
// different contracts, parent contracts are searched from
// right to left, and in depth-first manner.

// 계약은 여러 부모 계약에서 상속될 수 있습니다.
// 함수가 호출될 때 다음에서 여러 번 정의됩니다.
// 다른 계약, 부모 계약은 다음에서 검색됩니다.
// 오른쪽에서 왼쪽으로, 깊이 우선 방식으로.

contract D is B, C {
    // D.foo() returns "C"
    // since C is the right most parent contract with function foo()
    // 왜냐하면 C는 함수 foo()를 가진 대부분의 상위 계약이기 때문이다.
    function foo() public pure override(B, C) returns (string memory) {
        return super.foo();
    }
}

contract E is C, B {
    // E.foo() returns "B"
    // since B is the right most parent contract with function foo()
    // 왜냐하면 B는 함수 foo()를 가진 대부분의 상위 계약이기 때문이다.
    function foo() public pure override(C, B) returns (string memory) {
        return super.foo();
    }
}

// Inheritance must be ordered from “most base-like” to “most derived”.
// Swapping the order of A and B will throw a compilation error.
// 상속은 "가장 기본적인"에서 "가장 파생된" 순서로 정렬되어야 합니다.
// A와 B의 순서를 바꾸면 컴파일 오류가 발생합니다.
contract F is A, B {
    function foo() public pure override(A, B) returns (string memory) {
        return super.foo();
    }
}

 

Try on Remix

'Programming Language > Solidity' 카테고리의 다른 글

Solidity - Calling Parent Contracts  (0) 2023.01.04
Solidity - Shadowing Inherited State Variables  (0) 2022.12.31
Solidity - Constructor  (0) 2022.12.30
Solidity - Events  (0) 2022.12.29
Solidity - Function Modifier  (0) 2022.12.28

관련글 더보기