2011-10-05 50 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