I want to print out the information for the children inside a vector, utilizing a shared pointer class that utilizes an Abstract base class. I cannot figure out the right way to overload it however. Maybe I should use some polymorph method for print..
Error message
Code:
|25|error: 'std::ostream& shared_pointer_class::operator<<(std::ostream&, const Shared_class&)' must take exactly one argument|
||In function 'int main()':|
|58|error: variable 'std::ofstream os' has initializer but incomplete type|
|59|error: 'ostream_iterator' was not declared in this scope|
|59|error: expected primary-expression before 'const'|
|59|error: expected ';' before 'const'|
|60|error: 'sp_out' was not declared in this scope|
||=== Build finished: 6 errors, 0 warnings ===|
Code
Code:
#include <iostream>
#include <vector>
using namespace std;
// ABC class
class Shared_class
{
public:
Shared_class(){}
virtual void print() = 0;
virtual ~Shared_class(){};
virtual Shared_class * clone() = 0;
private:
double x,y;
};
// The shared pointer class
class shared_pointer_class
{
public:
shared_pointer_class(){ spc = 0;}
shared_pointer_class(Shared_class * spc_in){ spc = spc_in; }
~shared_pointer_class(){};
ostream& operator<<( ostream &os, const Shared_class & spc_in){ return os << spc_in.print(); } // Here is the error
private:
Shared_class * spc;
};
// Inherited classes
class a : public Shared_class
{
public:
a(double ix, double iy) : x(ix),y(iy) {}
void print(){ cout << "(" << x << "," << y << ") " << endl; }
a * clone(){ return new a(* this); }
private:
double x,y;
};
class b : public Shared_class
{
public:
b(double ix, double iy, double iz) : x(ix),y(iy), z(iz) {}
void print() { cout << "(" << x << "," << y << "," << z << ") " << endl;}
b * clone(){ return new b(* this); }
private:
double x,y,z;
};
int main()
{
vector<shared_pointer_class> shared_container;
shared_container.push_back( shared_pointer_class(new a(4,10)) );
shared_container.push_back( shared_pointer_class(new b(6,7,1)) );
ofstream os("output.txt");
ostream_iterator<const shared_pointer_class> sp_out(os,"\n");
copy( shared_container.begin(), shared_container.end(), sp_out);
os.close(); // Error
return 0;
}
Thanks in advance!
I can declare the operator as friend to get rid of the two input arguments error but then I get this error:
Code:
In function 'std::ostream& operator<<(std::ostream&, const Shared_class&)':|
25|error: passing 'const Shared_class' as 'this' argument of 'virtual void Shared_class::print()' discards qualifiers|
|25|error: no match for 'operator<<' in 'os << ((const Shared_class*)spc_in)->Shared_class::print()'|
+ the same as above