// A2.1.cpp : Defines the entry point for the console application. // // Given the declarations: // // class D : public B { … private: std::string s; std::istream &is; } // // Can you write an assignment operator for this class? If not, why not? // How would you support both a string and an input stream as data members // in a way that allows assignment? Please write an assignment operator // for this D class. You may assume that the only data members of D are // those shown. #include "stdafx.h" #include #include class B {}; class D : public B { public: D() : B(), s("default string"), pIstream(NULL) {} D(const D &d) : B(d), s(d.s), pIstream(d.pIstream) {} void setStream(std::istream& in) { pIstream = ∈ } void setString(const std::string& str) { s = str; } bool read(); void write(std::ostream& out) { out << s.c_str(); } D& operator=(const D& d); private: std::string s; std::istream* pIstream; }; //// answer ///////////////////// D& D::operator =(const D& d) { if(this == &d) return *this; (B&)(*this) = d; pIstream = d.pIstream; s = d.s; return *this; } ///////////////////////////////// bool D::read() { if(!pIstream->good()) return false; std::string line; std::getline(*pIstream,line); if(line.size() == 0) return false; s += line; s += '\n'; return (pIstream->good()); } int _tmain(int argc, _TCHAR* argv[]) { std::cout << "\n Exam A2 - Question #1 " << "\n =======================\n"; D d1; d1.setStream(std::cin); d1.setString("first object:\n"); D d2; d2 = d1; d2.write(std::cout); d2.setString(""); bool ok; do { std::cout << "\nplease enter some text from keyboard, enter to quit:\n"; ok = d2.read(); std::cout << "\n---- writing what was read from keyboard ----\n"; d2.write(std::cout); std::cout << std::endl; } while(ok); std::cout << "\n\n"; return 0; }