Never Call Virtual Functions during Constructio...

  • 代碼

1. java

class Bird {

	public Bird() {
		show();
	}

	public void show() {
		System.out.println("hey, I'm a bird.");
	}
}

class Eagle extends Bird {
	private String name = "littleEgale";

	public Eagle(String name) {
		this.name = name;
	}

	@Override
	public void show() {
		System.out.println("I'm a bald eagle, my name is " + name + '.');
	}

}

public class VirtualTester {

	public static void main(String[] args) {
		new Eagle("java");
	}

}

2. c++

#include <iostream>
#include <string>
using namespace std;

class Bird {
public:
    Bird() {
        show();
    }

    virtual void show() {
        cout << "hey, I'm a bird." << endl;
    }

};


class Eagle : public Bird {
private :
    string name;
public:
    Eagle(const string &name):name(name)
    {
    }

    void show() {
        cout << "I'm a bald eagle, my name is " << name
             << "." <<endl;
    }
};

int main() {
    Eagle("cPlusPlus");
}

3. python

class Bird():
    def __init__(self):
        self.show()

    def show(self):
        print("hey, I'm a bird.")

class Eagle(Bird):
    
    def __init__(self,name):
        self.__name = name  # 1
        Bird.__init__(self) # 2

    def show(self):
        print("I'm a bald eagle, my name is",self.__name,'.')


Eagle('python')
  • 運行結果:

java:       I'm a bald eagle, my name is null.java

c++:       hey, I'm a bird.python

python:   I'm a bald eagle, my name is python.ios

  • 分析

      Item 9:Never Call Virtual Functions during Construction or Destruction. Effective C++c++

      Puzzle 49: Larger Than Life.  Java Puzzlerside

  • 結論:

        不在構造和析構過程當中調用virtual函數, 適用於基類初始化限定在子類初始化以前的語言。 一個設計良好的繼承體系,應該避免在基類構造函數中直接或間接的調用被子類重載的方法。函數

相關文章
相關標籤/搜索