回复 8楼 寒风中的细雨
版主你好,实际上我是在看EC时看到这个条款时遇到这个问题的
Item 9: Never call virtual functions during construction or destruction
它里面举了一个Transaction 的例子
class Transaction {
// base class for all
public:
// transactions
Transaction();
virtual void logTransaction() const = 0;
// make type-dependent
// log entry
...
};
Transaction::Transaction()
// implementation of
{
// base class ctor
...
logTransaction();
// as final action, log this
}
// transaction
class BuyTransaction: public Transaction {
// derived class
public:
virtual void logTransaction() const;
// how to log trans-
// actions of this type
...
};
class SellTransaction: public Transaction {
// derived class
public:
virtual void logTransaction() const;
// how to log trans-
// actions of this type
...
};
Consider what happens when this code is executed:
BuyTransaction b;
并且在后边他解释到
During base class construction of a derived class object, the type of the object is that of the base class. Not only do virtual functions resolve to the base class, but the parts of the language using runtime type information (e.g., dynamic_cast (see Item 27) and typeid) treat the object as a base class type. In our example, while the transaction constructor is running to initialize the base class part of a BuyTransaction object, the object is of type TRansaction. That's how every part of C++ will treat it, and the treatment makes sense: the BuyTransaction-specific parts of the object haven't been initialized yet, so it's safest to treat them as if they didn't exist. An object doesn't become a derived class object until execution of a derived class constructor begins.
所以才有了我在里面写下typeid的代码,并且我测试过,确实没问题,输出的确实是class Transaction ,所以才有了我提出的既然在构造时表现出来的是Transaction ,那么怎么还可以调用继承类的成员函数的疑问,实际上在没看这个之前倒是没有考虑这么多的