关于操作员超载

时间:2017-11-16 23:01:57

标签: c++ c++11 operator-overloading codeblocks ifstream

我在c++中有一个程序会重载此运算符>>。这个运算符负责要求输入文本cin >>我的问题是如果我必须使用同一个运算符而不是ifstream条目,我该怎么做。

用代码编辑

istream & operator >> (istream & Read, Person & ObjPers) {
     cout << "\ n \ n Enter name of Person:";
     Lee >> ObjPers.NomPers;
     cout << "\ n \ n Enter year of birth:";
     Read >> ObjPers.AnioNac;
     cout << "\ n \ nEnter place of birth:";
     Read >> ObjPers.LugNac;
     cout << "\ n \ nIs it alive ?:";
     Read >> ObjPers.Vive;
     return Read;
}

如果我需要使用相同的运算符但使用不同的ifstream >> variable我需要做什么?

EDIT2:

当我重载ostream&lt;&lt;发生这种情况:

   ostream & operator << (ostream & Write, Persona & ObjPers) {
    Write << "\ n \ nData of the Person \ n";
    Type << "\ nName:" << ObjPers.NomPers;
    Write << "\ nPlace of birth:" << ObjPers.LugNac;
    Write << "\ nYear of birth:" << ObjPers.AnioNac;
    if (ObjPers.live == 1)
    Write << "\ nIt is alive. \ N";
    else
    Write << "\ nNot alive. \ N";
         return Write;

    }

当我尝试将ofstream与&lt;&lt;运算符我不能重载运算符首先运行

void BinaryTree <T> :: Save (NodeTree <T> * p, ofstream & out)
{
     if (p) {

        Save (p-> Sonleft, out);
         exit << p-> Info;

        Save (p-> SonRigth, out);

     }
     cout << endl;

}

1 个答案:

答案 0 :(得分:0)

实施operator>>功能时

  1. 请勿在其实施中使用std::cinstd::cout
  2. 假设用户知道要为这样的对象输入什么内容。
  3. 使用istream的完全限定名称,即使用std::istream& Read istream& Read {}进行std::istream& operator>>(std::istream& in, Person & ObjPers) { in >> ObjPers.NomPers; in >> ObjPers.AnioNac; in >> ObjPers.LugNac; in >> ObjPers.Vive; return in; }
  4. 我对你的职能的建议:

    std::istream& operator>>(std::istream& in, Person & ObjPers) {
       return (in >> ObjPers.NomPers
                  >> ObjPers.AnioNac
                  >> ObjPers.LugNac
                  >> ObjPers.Vive);
    }
    

    或将这些陈述合并为一个:

    public class Class1 {
    
        //Constructor
        public Class1(){}
    
        //Methods
        public ArrayList createArray(){
            //Your code here
        }
    
    }
    
    public class Class2 {
    
        //Constructor
        public Class2(ArrayList myArray){
            //Your code here    
        }
    
    }
    
    
    public class Test{
        Class1 c1 = new Class1;
        ArrayList array = c1.createArray();
        Class2 c2 = new Class2(array);
    }