2011-10-05 90 views
0

這是一個與cgal相關的問題,但我認爲它也是一個普通的C++問題,所以我在這裏問它。在父函數中沒有更新子對象函數中的賦值對象

我正在嘗試使用Alpha_shape_2類,並在名爲GetAlphaShalCg的子例程中將它分配給AlphaShapeCg類。問題是Alpha_shape_2中的某些功能沒有返回正確的結果。

這是我的代碼,這是很簡單,但我不太清楚爲什麼會存在分配Alpha_shape_2在子程序的包裝之間的差異,然後訪問該成員在父母常規和直接訪問Alpha_shape_2

如果您安裝了CGAL,以下是您可以編譯和使用的完整代碼。

#include <CGAL/Exact_predicates_inexact_constructions_kernel.h> 
#include <CGAL/algorithm.h> 
#include <CGAL/Delaunay_triangulation_2.h> 
#include <CGAL/Alpha_shape_2.h> 

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <list> 


typedef CGAL::Exact_predicates_inexact_constructions_kernel K; 

typedef K::FT FT; 

typedef K::Point_2 Point; 
typedef K::Segment_2 Segment; 


typedef CGAL::Alpha_shape_vertex_base_2<K> Vb; 
typedef CGAL::Alpha_shape_face_base_2<K> Fb; 
typedef CGAL::Triangulation_data_structure_2<Vb,Fb> Tds; 
typedef CGAL::Delaunay_triangulation_2<K,Tds> Triangulation_2; 

typedef CGAL::Alpha_shape_2<Triangulation_2> Alpha_shape_2; 


template <class OutputIterator> 
bool 
file_input(OutputIterator out) 
{ 
    std::ifstream is("./data/fin", std::ios::in); 

    if(is.fail()){ 
    std::cerr << "unable to open file for input" << std::endl; 
    return false; 
    } 

    int n; 
    is >> n; 
    std::cout << "Reading " << n << " points from file" << std::endl; 
    CGAL::copy_n(std::istream_iterator<Point>(is), n, out); 

    return true; 
} 

//------------------ main ------------------------------------------- 


struct AlphaShapeCg 
{ 

    Alpha_shape_2 *AlphaShape; 
}; 

void GetAlphaShalCg(AlphaShapeCg *ashape, std::list<Point> points) 
{ 

     Alpha_shape_2 A(points.begin(), points.end(), 
      FT(100000), 
      Alpha_shape_2::GENERAL); 
    ashape->AlphaShape=&A; 
} 



int main() 
{ 
    std::list<Point> points; 
    if(! file_input(std::back_inserter(points))){ 
    return -1; 
    } 

    AlphaShapeCg ashape; 


    GetAlphaShalCg(&ashape, points); 

    Alpha_shape_2 *APtrs=(ashape.AlphaShape); 
    int alphaEigenValue = APtrs->number_of_alphas(); // gives incorrect result; alphaEigenValue=0 

    //Alpha_shape_2 A(points.begin(), points.end(), 
    // FT(100000), 
    // Alpha_shape_2::GENERAL); 
    // int alphaEigenValue = APtrs->number_of_alphas(); // gives correct result; alphaEigenValue!=0 

} 

更新:我試圖用

Alpha_shape_2 =new A(points.begin(), points.end(), FT(100000), Alpha_shape_2::GENERAL); 

但這個代碼根本不會因爲這個錯誤的編譯:

error C2513: 'CGAL::Alpha_shape_2' : no variable declared before '='

回答

1

你分配一個指針指向一個局部變量當你退出該功能時會被破壞。

如果你想在函數中創建對象並返回它的地址 - 你應該使用動態分配(new它,當你完成它時不要忘記delete)。

+0

你能不能在這部分明確 - **你應該使用動態分配**? – Graviton

+0

爲了您的記錄,我嘗試過'Alpha_shape_2 = new A(points.begin(),points.end(),FT(100000),Alpha_shape_2 :: GENERAL);'但這段代碼無法編譯,查看更新的問題。 – Graviton

+0

@Graviton - 做'Alpha_shape_2 <一些變量名稱> =新.... - 你必須給變量一個名稱,而不僅僅是類型。 – littleadv