Wednesday 6 February 2019

C++ Function Overloading

#include <iostream>
using namespace std;
class CStudent {
public: int nAge;
};
ostream&operator<<(ostream& o, const CStudent &s) {
 o << s.nAge;
 return o;
}
int main() {
 CStudent s;
 s.nAge = 5;
 cout << s << "hello";
 return 0; 
}
 — — — — — — — — — 
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
class Complex {
 double real, image;
public:
 Complex(double r = 0, double i= 0) :real(r), image(i) {};
 friend ostream & operator<<(ostream & os, const Complex&c);
 friend istream & operator>>(istream & is, Complex&c);
};
ostream & operator<<(ostream & os, const Complex & c) {
 os << c.real << "+" << c.image << "i";
 return os;
}
istream & operator>>(istream & is, Complex & c) {
 string s;
 is >> s;
 int pos = s.find("+", 0);
 string sTmp = s.substr(0, pos);
 c.real = atof(sTmp.c_str());
 sTmp = s.substr(pos + 1, s.length() - pos - 2);
 c.image = atof(sTmp.c_str());
 return is;
}
int main() {
 Complex c;
 int n;
 cin >> c >> n;
 cout << c << "," << n;
 return 0; 
}

String &String::operator = (const String & s) {
 if (str == str.str) return *this;
 if (str) delete[]str;
 if(s.str){
  str = new char[strlen(s.str) + 1];
  strcpy(str, s.str);
 }
 else
  str = NULL;
 return *this;
}
为了避免两个指针指向同一string,重复释放内存的问题,我们用strcpy。
复制构造函数也一样
String::String(String & s) {
 if (s.str) {
  str = new char[strlen(s.str) + 1];
  strcpy(str, s.str);
 }
 else
  str = NULL;
}

No comments:

Post a Comment