Originally Posted by
master5001
Almost. A struct can be initialized via the old C style way (i.e. MyStruct foo = {member1, member2, member3}) whereas a class can't.
Really? Hmmm wonder why this works:
Code:
#include <iostream>
using namespace std;
class Foo {
public:
int x;
int y;
};
struct Bar {
int x;
int y;
};
ostream& operator<< (ostream& o, const Foo& f)
{
return o<<f.x<<' '<<f.y;
}
ostream& operator<< (ostream& o, const Bar& b)
{
return o<<b.x<<' '<<b.y;
}
int main()
{
Foo fee = {1,2};
Bar bee = {3,4};
cout<<fee<<endl;
cout<<bee<<endl;
}
But this won't
Code:
#include <iostream>
using namespace std;
class Foo {
public:
int x;
int y;
private:
int z;
friend ostream& operator<< (ostream&, const Foo& );
};
struct Bar {
int x;
int y;
private:
int z;
friend ostream& operator<< (ostream&, const Bar& );
};
ostream& operator<< (ostream& o, const Foo& f)
{
return o<<f.x<<' '<<f.y;
}
ostream& operator<< (ostream& o, const Bar& b)
{
return o<<b.x<<' '<<b.y;
}
int main()
{
Foo fee = {1,2,3};
Bar bee = {4,5,6};
cout<<fee<<endl;
cout<<bee<<endl;
}
struct.cpp: In function `int main()':
struct.cpp:35: `fee' must be initialized by constructor, not by `{...}'
struct.cpp:36: `bee' must be initialized by constructor, not by `{...}'
Edit:
ANSI/ISO Standard 9.4
A structure is a class defined with the class-key struct; its members and base classes (clause 10) are public by default