Java vs C++(五) 构造器中调用虚函数
java: 行为正确,表现多态
package com.cisco.test;
class Child extends Base{
public void init(){
System.out.println("child init");
}
}
public class Base {
public Base() {
init();
}
public void init(){
System.out.println("base init");
}
public static void main(String[] args){
new Child();
}
}
child init
/*
* Child.cpp
*
* Created on: Oct 23, 2013
* Author: jiafu
*/
#include "Child.h"
#include <iostream>
namespace std {
Child::Child() {
// TODO Auto-generated constructor stub
}
void Child::init(){
cout<<"child init"<<endl;
}
Child::~Child() {
// TODO Auto-generated destructor stub
}
} /* namespace std */
c++:
/*
* Child.h
*
* Created on: Oct 23, 2013
* Author: jiafu
*/
#ifndef CHILD_H_
#define CHILD_H_
#include "Base.h"
namespace std {
class Child: public std::Base {
public:
Child();
virtual ~Child();
virtual void init();
};
} /* namespace std */
#endif /* CHILD_H_ */
/*
* Base.h
*
* Created on: Oct 23, 2013
* Author: jiafu
*/
#ifndef BASE_H_
#define BASE_H_
namespace std {
class Base {
public:
Base();
virtual void init();
virtual ~Base();
};
}
#endif
/*
* Base.cpp
*
* Created on: Oct 23, 2013
* Author: jiafu
*/
#include "Base.h"
#include <iostream>
namespace std {
Base::Base() {
Base::init();
}
Base::~Base() {
}
void Base::init(){
cout<<"base init"<<endl;
}
} /* namespace std */
调用:
Child child;
Base& b1=child;
b1.init();
Base* b2=new Child;
b2->init();
构造时不表现多态,调用方法时表现了。