这是什么问题。它没有按预期工作。

我希望<

#include<iostream>

using namespace std;

class a
{
private:
   string name;
   int age;
   unsigned long int salary;
public:
   friend ostream& operator << (ostream& ,a );
   friend istream& operator << (istream& ,a );
};

ostream& operator << (ostream& dout,a a1){
   cout<<"Name = "<< a1.name<<"Age = "<<a1.age<<"Salary = "<<a1.salary<<end;
   return dout;
}
istream& operator << (istream& din,a& a1){
   cout<<"Enter Your Name , Age  , Salary .....Press Enter To Seperate New Value"<<end;
   cin>>a1.name>>a1.age>>a1.salary;
}
main(int argc, char const *argv[])
{
   a a1;

   cin<<a1;
   cout<<a1;
   return 0;
}

错误过长。
->

最佳答案

我不确定为什么要这样做,但是有可能。请记住,仅仅因为您可以做某事并不意味着您应该做那件事(请参阅C++ Faq Law of Least Surprise
除了违反最不惊奇的法则,您还可以做您想做的事情,您的代码中只有几个简单的编译错误,一旦修复,就可以正常工作(有关示例,请参见here)。

这是使其进行编译的更改:

friend istream& operator << (istream& ,a& ); // Note the addition of the &

// Here the variabe is dout, so change to dout. I also added some spacing
ostream& operator << (ostream& dout,a a1){
   dout<<"Name = "<< a1.name<<" Age = "<<a1.age<<" Salary = "<<a1.salary<<endl;
   return dout;
}

// Here you are using din, so you need to change to din, also you had end instead of endl
istream& operator << (istream& din,a& a1){
    cout<<"Enter Your Name , Age  , Salary .....Press Enter To Seperate New Value"<<endl;
    din>>a1.name>>a1.age>>a1.salary;
    return din;
}

只是这样,完整的代码也对您而言很容易。这是您的整个程序,其中包含要进行编译的更改。
#include<iostream>

using namespace std;

class a
{
private:
   string name;
   int age;
   unsigned long int salary;
public:
   friend ostream& operator << (ostream& ,a );
   friend istream& operator << (istream& ,a& );
};

ostream& operator << (ostream& dout,a a1){
   dout << "Name = "<< a1.name <<" Age = "<< a1.age <<" Salary = "<< a1.salary << endl;
   return dout;
}
istream& operator << (istream& din,a& a1){
   cout <<"Enter Your Name , Age  , Salary .....Press Enter To Seperate New Value" << endl;
   din >> a1.name >> a1.age >> a1.salary;
   return din;
}
main(int argc, char const *argv[])
{
   a a1;

   cin<<a1;
   cout<<a1;
   return 0;
}

现在,如果要遵循“最小定律”,则可以将istream运算符重载更改为使用>>而不是<<,并将控制台文本移出>>运算符重载,并在读取值之前将其呈现给用户。
#include<iostream>

using namespace std;

class a
{
private:
   string name;
   int age;
   unsigned long int salary;
public:
   friend ostream& operator << (ostream& ,a );
   friend istream& operator >> (istream& ,a& );
};

// Note - Changed variable 'dout' to 'os' for clarity
ostream& operator << (ostream& os, a a1){
   os << "Name = " << a1.name << " Age = " << a1.age << " Salary = "<< a1.salary << endl;
   return os;
}

// Changed variable from 'din' to 'is' for clarity
istream& operator >> (istream& is,a& a1){
   is >> a1.name >> a1.age >> a1.salary;
   return is;
}

main(int argc, char const *argv[])
{
   a a1;

   cout << "Enter Your Name , Age  , Salary .....Press Enter To Seperate New Value" << endl;
   cin >> a1;
   cout << a1;
   return 0;
}

09-07 04:59