// SPDX-License-Identifier: MIT pragma solidity ^0.8.17;
/* Graph of inheritance A / \ B C / \ / F D,E
*/ contract A { //需要被重写的函数加上virtual修饰符 function foo() public pure virtual returns(string memory) { return "A"; } } contract B is A{ function foo() public pure override virtual returns (string memory) { return "B"; } } contract C is A { function foo() public pure override virtual 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 { //多继承时候需要给override传入重写合约 function foo() public pure override(B, C) returns (string memory) { return super.foo();//返回“C” } } contract E is C,B { function foo() public pure override(C, B) returns (string memory) { return super.foo();//返回“B” } } contract F is A, B { //必须把父合同放前面(A是B的父合同) //此时是孙子合同 //调换A跟B会发生编译错误 function foo() public pure override(B, A) returns (string memory) { return super.foo(); } }
pragma solidity ^0.8.17; //SPDX-License-Identifier:MIT contract A { event log(string mess); function foo() public virtual { emit log("A.foo() is called."); } function bar() public virtual { emit log("A.bar() is called"); } } contract B is A{ function foo() override virtual public { emit log("B.foo() is called"); super.foo(); } function bar() override virtual public { emit log("B.bar() is called"); A.bar(); } } contract C is A { function foo() override virtual public { emit log("C.foo() is called"); super.foo(); } function bar() override virtual public { emit log("C.bar() is called"); A.bar(); } } contract D is B, C { function foo() override(B, C) public { super.foo();//D.foo()->C.foo()->A.foo()错误理解一,错误理解二super会自右向左把自己的父类都调用一遍 //D.foo()->C.foo()->B.foo()->A.foo() //super就是有父类的时候(指的是最开始调用的合约)会调用父类,没有的时候就调用其爷类 } function bar() override(B, C) public {//就算override(C, B)也同样是D.bar()->C.bar()->A.bar() super.bar();//D.bar()->C.bar()->A.bar() } }