假设我有两个c++类:
class A
{
public:
A() { fn(); }
virtual void fn() { _n = 1; }
int getn() { return _n; }
protected:
int _n;
};
class B : public A
{
public:
B() : A() {}
virtual void fn() { _n = 2; }
};
如果我写下面的代码:
int main()
{
B b;
int n = b.getn();
}
有人可能认为n被设为2。
结果是n被设为1。为什么?
解决这个问题的一个方法是使用工厂方法来创建对象。
为你的类层次结构定义一个公共基类,其中包含一个虚拟方法afterConstruction():
class Object
{
public:
virtual void afterConstruction() {}
// ...
};
定义一个工厂方法:
template< class C >
C* factoryNew()
{
C* pObject = new C();
pObject->afterConstruction();
return pObject;
}
像这样使用它:
class MyClass : public Object
{
public:
virtual void afterConstruction()
{
// do something.
}
// ...
};
MyClass* pMyObject = factoryNew();
Firstly,Object is created and then we assign it 's address to pointers.Constructors are called at the time of object creation and used to initializ the value of data members. Pointer to object comes into scenario after object creation. Thats why, C++ do not allows us to make constructors as virtual .
.another reason is that, There is nothing like pointer to constructor , which can point to virtual constructor,because one of the property of virtual function is that it can be used by pointers only.
虚函数用于动态赋值,因为构造函数是静态的,所以我们不能将它们设为虚函数。
我刚刚在一个程序中出现了这个错误。
我有这样的想法:如果方法在构造函数中被标记为纯虚函数会发生什么?
class Base {
public:
virtual int getInt() = 0;
Base(){
printf("int=%d\n", getInt());
}
};
class Derived : public Base {
public:
virtual int getInt() override {return 1;}
};
和…有趣的事情!你首先得到编译器的警告:
warning: pure virtual ‘virtual int Base::getInt() const’ called from constructor
和一个来自ld的错误!
/usr/bin/ld: /tmp/ccsaJnuH.o: in function `Base::Base()':
main.cpp:(.text._ZN4BaseC2Ev[_ZN4BaseC5Ev]+0x26): undefined reference to `Base::getInt()'
collect2: error: ld returned 1 exit status
这是完全不合逻辑的,你只得到一个警告从编译器!