我得到了一個正常工作的C++面向對象程序。我決定修改它,通過添加一些polimorpysm來定義具有虛擬方法的類層次結構。當我調用虛擬方法時,它會產生錯誤分割錯誤,可能是因爲我在對象中有垃圾。通過使用C++中的虛擬方法分段錯誤
這是呼叫和熱身
GPUAntColony *colony; // Base class
GPUAntColonyConfiguration config;
set_config(config);
set_initial_pheromone(problem, config);
colony = (GPUAntColony *)new GPUSimpleAntColony(problem, config);//inhereted class
colony->run(); //Virtual method
現在讓我告訴你的基類
class GPUAntColony {
private:
void reset_ants() {
for(unsigned int i=0; i<configuration_.number_of_ants;i++) {
ants_[i]= Util::random_number(problem_->number_of_vertices());
}
}
void initialize_Pheromone(){
for(unsigned int i=0; i<problem_->number_of_vertices()*problem_->number_of_vertices();i++) {
pheromones_[i]=(float)configuration_.initial_pheromone;
}
}
protected:
float * pheromones_;
float alpha_;
float beta_;
unsigned int iterations;
GPUAntColonyConfiguration::LocalSearchType local_search_type_;
GPUAntColonyConfiguration configuration_;
unsigned int * ants_;
GPUOptimizationProblem *problem_;
public:
///Class Constructor for the Class GPU Ant Colony
GPUAntColony(GPUOptimizationProblem *problem, const GPUAntColonyConfiguration &config){
iterations=4096;
problem_ = problem; // Including distance array
configuration_ = config;
ants_= (unsigned int*) malloc(config.number_of_ants*sizeof(unsigned int));
pheromones_ = (float *) malloc(problem->number_of_vertices()*problem->number_of_vertices()*sizeof(float));
alpha_ = config.alpha;
std::cout << "alpha_ " << alpha_ << std::endl;
beta_ = config.beta;
local_search_type_ = config.local_search;
}
virtual void run();
virtual ~GPUAntColony() {
delete problem_;
free(ants_);
free (pheromones_);
};
};
子類的定義
class GPUSimpleAntColony : public GPUAntColony{
public:
GPUSimpleAntColony(GPUOptimizationProblem *problem, const GPUAntColonyConfiguration &config);
void run();
};
最後的這種方法的實施
void GPUAntColony::run(){
reset_ants();
initialize_Pheromone();
}
GPUSimpleAntColony::GPUSimpleAntColony(GPUOptimizationProblem *problem, const GPUAntColonyConfiguration &config):GPUAntColony(problem, config) {
}
void GPUSimpleAntColony::run() {
GPUAntColony::run();
antColonyGPULauncher(configuration_.number_of_ants, problem_->number_of_vertices(), problem_->get_distances(), pheromones_,ants_,alpha_, beta_,
configuration_.evaporation_rate, iterations, 0, 0, 0, 0, ACO_SIMPLE);
}
希望你能幫助我。
非常感謝提前。
什麼是轉儲的堆棧跟蹤,當你拿到賽格故障?這可能與虛擬以及與'antColonyGPULauncher' – 2010-10-18 16:14:03
有關的所有事情都沒有關係是的,這就是我雖然在開始但antColonyGPUlauncher沒有錯,因爲沒有達到這行代碼。分段錯誤是在調用虛擬方法run()時。 – Jose 2010-10-18 16:39:32
@Jose:你可以添加堆棧跟蹤嗎? GDB到你的問題呢? – 2010-10-18 16:45:37