#include<iostream>
using namespace std;
class Nibble
{
private:
union
{
int number : 4;
};
public:
Nibble(int=0);
friend ostream& operator<<(ostream&,const Nibble&);
friend istream& operator>>(istream&,Nibble&);
};
inline Nibble::Nibble(int n) : number(n) { cout << "constructor.." << endl;}
ostream& operator<<(ostream& nout,const Nibble& n)
{
return nout << n.number;
}
istream& operator>>(istream& nin,Nibble& n)
{
/* error here
// error : In function `std::istream& operator>>(std::istream&, Nibble&)':
//cannot bind bitfield `n->Nibble::<anonymous>.Nibble::<anonymous union>::number' to `int&'
*/
return nin >> n.number;
}
int main()
{
Nibble n1;
cin >> n1;
cout << "Value of Nibble is:" << n1 << endl;
getchar();
return 0;
}
++C LOVER 0 Newbie Poster
Recommended Answers
Jump to Post>>Now you can use the usual union membership operator to assign values to individual fields:
NO YOU CAN'T. The union is used to assign the same memory location to several different POD (Plain Old Data) type objects. All the objects in the union below occupy the same space, and …
Jump to PostI have posted the answer yesterday but DaniWeb site discard it (why?).
My guess is that you forgot to hit the Submit Reply button. I have never seen someone's post just disappear without reason.
In general bit fields are useless part of C (and C++) language (next to nothing).
Better …
Jump to PostIn general bit fields are useless part of C (and C++) language (next to nothing).
Better get it out of your head and go on...2. Alas, I have used bit fields over 30 years ago in C...
So ... bit fields aren't useless aftersll :)
Jump to Post>>BUT STILL ALL THESE Replies ARE NOT helping me
BECAUSE YOU ARE NOT LISTENING!Here is an example how to do it.
#include <fstream> using namespace std; union myunion { unsigned int x; struct mystruct { unsigned int bit1:1; unsigned int bit3:1; unsigned int bit4:1; unsigned …
Jump to PostThe code I posed only accesses 8 of the int's 32 bits (assuming 32-it compiler).
All 19 Replies
CoolGamer48 65 Posting Pro in Training
Alex Edwards 321 Posting Shark
CoolGamer48 65 Posting Pro in Training
++C LOVER 0 Newbie Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
ArkM 1,090 Postaholic
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
ArkM 1,090 Postaholic
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
ArkM 1,090 Postaholic
++C LOVER 0 Newbie Poster
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Alex Edwards 321 Posting Shark
Ancient Dragon 5,243 Achieved Level 70 Team Colleague Featured Poster
Alex Edwards 321 Posting Shark
ArkM 1,090 Postaholic
Duoas 1,025 Postaholic Featured Poster
++C LOVER 0 Newbie Poster
Alex Edwards 321 Posting Shark
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.