//一种错误的方式:在基类的构造函数中去调用virtual函数 #include<iostream> using namespace std; #if 0 class Transcation { public: Transcation() { //... logTran(); } ~Transcation() {} virtual void logTran() = 0; }; class BuyTranscation : public Transcation { void logTran() { //... cout << "this is BuyTranscation's ctor"; } }; int main() { BuyTranscation bt; //不能够在构造函数中调用virtual函数,因为此时它并没有指向具体的函数 return 0; } #else //一种好的做法是将Log函数改为non-virtual,然后要求子类ctor传递必要的信息给到Trans的构造函数.这样仍然实现了在父类的构造函数中调用Log函数,并且不会存在问题. class Trans { public: Trans(string param) { string str = "Trans Speaks:"; cout << (str + param).c_str() << endl; LogTrans(); } void LogTrans() { cout << "##########Log###########" << endl; } }; class BuyTrans : public Trans { public: BuyTrans(string param) : Trans(CreateLog(param)) //在子类构造函数执行之前就让基类构造函数进行执行. { } private: static string CreateLog(string param) { string str = "Hello, this is: "; return str + param; } }; int main() { BuyTrans btt("btt"); return 0; } #endif