2011-11-22 51 views
1

对不起,我不知道该怎么说。基本上我有一个指向形状对象的空指针,当输入一些输入时,我希望它们是这个形状对象的值;输入到指针并返回该指针的方法?

shape *s = (shape *) 0; 
cin >> *s; 
if (s) 
    cout << "Shape" << (*s) << '\n'; 
else if (! cin.bad()) 
    cout << "Read reached EOF\n"; 
else 
    cout << "Read failed\n"; 

我重载< <运营商像这样,它要求的是什么形状的平局方法;

std::ostream& operator<< (std::ostream &os, shape &s){ 
    s.draw(); 
    return os; 
} 

我正在努力尝试读取我的值到指针。我的数据的输入类型是这样的;

< Circle: (3,1) 1 > 

我重载了>>运算符;

std::istream& operator>> (std::istream &is, shape &s){ 
    char lessthan, greaterthan, opbrkt, clsbrkt, comma; 
    string shape_type; 
    double x1, y1, r, x2, y2, x3, y3; 

    if (is >> lessthan) { 
    if ('<' != lessthan) { 
     is.setstate(ios::badbit); 
     return is; 
    } 

    //Circle implemntation 
    if(is >> shape_type && shape_type == "Circle:"){ 
     if(!((is >> opbrkt) && (opbrkt = '('))) { 
     is.setstate(ios::badbit); 
     return is; 
     } 

     cout << "Yes" << i++; 
     if(!(is >> x1)){ 
     is.setstate(ios::badbit); 
     return is; 
     } 

     if(!(is >> comma && comma == ',')){ 
     is.setstate(ios::badbit); 
     return is; 
     } 

     if(!(is >> y1)){ 
     is.setstate(ios::badbit); 
     return is; 
     } 


     if(!(is >> clsbrkt && clsbrkt == ')')) { 
     is.setstate(ios::badbit); 
     return is; 
     } 

     if(!(is >> r)){ 
     is.setstate(ios::badbit); 
     return is; 
     } 

     if(!(is >> clsbrkt && clsbrkt == '>')) { 
     is.setstate(ios::badbit); 
     return is; 
     } 
    } 

    return is; 
    } 

    return is; 
} 

这基本上回升,这是一个圆圈,并把相关到变量以备后用,但我如何得到这个数据到的“指针在什么现在应该是圆形对象指向?

回答

1

您无法读入指针。你只能读入的对象:

shape s; 
std::cin >> s; 

// if you need a pointer for some reason: 
shape * p = &s; 

如果实际的目标在本质上是多态的,你可能想制作一个包装类,也许像这样:

class Shape 
{ 
    ShapeImpl * impl; // or better, `std::unique_ptr<ShapeImpl>` 
    // 
} 

class ShapeImpl { virtual ~ShapeImpl() { } }; 
class Circle : public ShapeImpl { /* ... */ } 

否则,你可能只是放弃超载流提取操作符的想法,而不是提供您自己的反序列化功能:

std::unique_ptr<Shape> read_shape(std::istream & is) 
{ 
    // ... 
    std::unique_ptr<Shape> p(new Circle); 
    // ... 
    return p; 
} 

std::unique_ptr<Shape> s(read_shape(std::cin)); 
1

哎呀!

shape *s = (shape *) 0; 
cin >> *s; 

您刚解除引用空指针。这是未定义的行为。你需要的是工厂方法。

shape* input() 
{ 
    string name; 
    cin >> name; 
    if(name == "circle") 
    { 
     double radius; 
     cin >> radius; 
     return new Circle(radius) 
    } 
    else if(name == "Rectangle") 
    { 
     .... 
     return new Rectangle(...); 
    } 
    else if .... 

} 
+0

感谢您的回复阿门!我会在哪里放这个函数,我会在重载的时候调用这个函数吗? – r0bb077

+0

这可能是一个独立的功能。 –

+0

阿门,对不起,我是一个绝对的业余爱好者!我如何为'cin >> * s'部分调用input()?! – r0bb077