- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在查看虚函数行为的示例。鉴于此测试代码,我对其行为有几个问题。
class A
{
public:
A(int x)
{
cout << "In A Constructor" << endl;
print();
}
~A(){
cout << "In A Destructor" << endl;
delete _val;
}
virtual void print() { cout << "A." << endl; }
private:
char* _val;
};
class B: public A
{
public:
B(int x, int y) : A(x)
{
_dVal = new char[y];
cout << "In B Constructor 1" << endl;
print();
}
B() : A(0)
{
_dVal = new char[1];
cout << "In B Constructor 2" << endl;
print();
}
~B(){
cout << "In B Destructor" << endl;
delete _dVal;
}
void print() { cout << "B" << endl; }
private:
char* _dVal;
};
int main(int argc, char** argv) {
A* p1 = new B();
p1->print();
delete p1;
return 0;
}
输出是:
In A Constructor
A.
In B Constructor 2
B
B
In A Destructor
1) 如果 A 类是唯一将它表示为虚函数的类,并且它是通过取消引用 (->) 调用的,为什么要为 B 类调用 print?2) 如果实际上正在调用构造函数,为什么 B 的析构函数从未被调用?
最佳答案
1) Why is print called for class B if class A is the only one denoting it as a virtual function and it is being called by dereference (->)?
这就是虚函数应该做的。指针p1
是A*
类型,但它实际上指向B
类型的对象。并且这种动态绑定(bind)仅在使用指针或对基类的引用处理派生类时发生。
另请注意,派生类中的重写函数也是 virtual (无论是否在其声明中使用了关键字 virtual)。
2) Why is the destructor for B never being called if the constructor is in fact being called?
B
的析构函数未被调用,因为您没有将基类(即 A::~A
)的析构函数声明为 virtual destructor .这种情况下的行为是未定义的。 B
的构造函数被调用,因为您通过 new B()
显式构造了 B
。
关于c++ - 虚函数签名不匹配及其行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42279541/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!