|
-
April 17th, 2012, 03:32 PM
#1
Serialization using std::ostream?
I am trying to add serialization to my DTO objects. I declared the methods in the class as follows outside of the public: and private: tags.
Code:
class DLLEXP DTO
{
friend std::ostream& operator<<(std::ostream& out, const DTO& obj);
friend std::ostream& operator>>(std::ostream& in, DTO& obj);
public:
......
private:
......
};
Then in the .cpp file I have:
Code:
std::ostream& operator<<(std::ostream& output, const DTO& obj)
{
if(output.good())
{
output.write((char*)&obj.id_, sizeof(obj.id_));
}
return output;
}
I am getting a compilation error:
error C2248: 'inform::http:  ata:  TO::id_' : cannot access private member declared in class 'inform::http:  ata:  TO'
Any hints on the problem. I thought just declaring the methods as friends was enough....
Mike B
-
April 17th, 2012, 04:03 PM
#2
Re: Serialization using std::ostream?
 Originally Posted by MikeB
I am getting a compilation error:
Any hints on the problem. I thought just declaring the methods as friends was enough....
Mike B
Access specifiers should not have any effect on friend functions as they are not members of the class.
This code works as expected, even if the friend function is explicitly in a private section:
Code:
#include <iostream>
using namespace std;
class DTO
{
private:
friend std::ostream& operator<<(std::ostream& out, const DTO& obj);
public:
DTO() {};
};
std::ostream& operator<<(std::ostream& output, const DTO& obj)
{
output << "DTO operator<< works!";
return output;
}
int main()
{
DTO dto;
cout << dto << endl;
return 0;
}
Something else must be causing your problem. Is it possible for you to post a more complete code example which we can compile for ourselves?
-
April 17th, 2012, 08:41 PM
#3
Re: Serialization using std::ostream?
 Originally Posted by Peter_B
Access specifiers should not have any effect on friend functions as they are not members of the class.
This code works as expected, even if the friend function is explicitly in a private section:
Code:
#include <iostream>
using namespace std;
class DTO
{
private:
friend std::ostream& operator<<(std::ostream& out, const DTO& obj);
public:
DTO() {};
};
std::ostream& operator<<(std::ostream& output, const DTO& obj)
{
output << "DTO operator<< works!";
return output;
}
int main()
{
DTO dto;
cout << dto << endl;
return 0;
}
Something else must be causing your problem. Is it possible for you to post a more complete code example which we can compile for ourselves?
Well, I tried to create a small example and reproduce the problem and the example compiles just fine, so, I think your right in that it must be something else causing the issue. I will keep plugging away at it and post something if I can reproduce the problem.
Thanks for the response.
Mike B
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|