c++ - 输入一个指针并返回该指针的方法?

标签 c++ pointers operator-overloading

抱歉标题,我不知道怎么说。基本上我有一个指向形状对象的空指针,当输入一些输入时,我希望它们成为这个形状对象的值;

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;
}

这基本上表明它是一个圆并将相关的变量放入变量中供以后使用,但是我如何将这些数据放入“s”指针以指向现在应该是圆对象的地方?

最佳答案

哎哟!!!

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 .... 

}

关于c++ - 输入一个指针并返回该指针的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8235092/

相关文章:

c++ - Visual Studio 2010 - 排除文件类型

c++ - 卡萨布兰卡 test_runner 因 std::bad_alloc 而失败

android - 无法从桌面套件更改为 Android 套件

C++ 使用 vector 重载输出

c++ - 我如何测试静态断言确实断言 "false"?

c - 为什么 `*(multi + row)` 生成指针地址而不是值?

C++指针查询

c++ - 你如何在 C 中使用 void 指针?

c++ - 构建前缀运算符

c++ - 自定义位数组 [] 和赋值运算符