代码之家  ›  专栏  ›  技术社区  ›  CW Holeman II

将对象开发为未初始化的变量char junk

  •  1
  • CW Holeman II  · 技术社区  · 7 年前

    Cevelop 对象到 char junk 作为“未初始化变量”。在这种情况下,解决问题的正确方法是什么?

    enter image description here

     friend std::ostream& operator<<(std::ostream& os_a, College& college_a) {
       return os_a <<  college_a.id_ + ' ' + college_a.name_;
     }
    
     friend std::istream& operator>>(std::istream& is_a, College& college_a) {
       char junk;
       return is_a >> college_a.id_ >> std::noskipws
           >> junk, std::getline(is_a, college_a.name_);  // name: between 1st space and endofline.
      }
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   NathanOliver    7 年前

    您有两个选择,可以初始化 junk 或者你可以把它扔掉。既然你知道你只需要吃一块你可以使用的空间 get 喜欢

    return is_a >> college_a.id_, is_a.get(), std::getline(is_a,college_a.name_);
    

    它也会做同样的事情。您还可以使代码更易于阅读

    is_a >> college_a.id_;
    is_a.get();
    std::getline(is_a,college_a.name_);
    return is_a;