Assignment from scalar to user-defined type

R

Richard Cavell

#include <stdint.h>

class uint128bit
{
public:
uint64_t bits0to63;
uint64_t bits64to127;

uint128bit operator= (uint128bit op2) { bits0to63 = op2.bits0to63;
bits64to127 = op2.bits64to127; return *this; }
uint128bit operator= (uint64_t op2) { bits0to63 = op2; bits64to127 =
0; return *this; }
};


int main (int argc, char * const argv[]) {
uint64_t a = 1LL;
uint128bit i128_a = a;
return 0;
}

This last line of code fails, saying: conversion from 'uint64_t' to
non-scalar type 'uint128bit' requested. What have I done wrong?
 
P

Peter Koch Larsen

Richard Cavell said:
#include <stdint.h>

class uint128bit
{
public:
uint64_t bits0to63;
uint64_t bits64to127;

uint128bit operator= (uint128bit op2) { bits0to63 = op2.bits0to63;
bits64to127 = op2.bits64to127; return *this; }
uint128bit operator= (uint64_t op2) { bits0to63 = op2; bits64to127 = 0;
return *this; }
};


int main (int argc, char * const argv[]) {
uint64_t a = 1LL;
uint128bit i128_a = a;
return 0;
}

This last line of code fails, saying: conversion from 'uint64_t' to
non-scalar type 'uint128bit' requested. What have I done wrong?

You need a way to construct a uint128bit from a uint64_t ;-)

class uint128bit
{
....
uint128bit(uint64_t rhs): bits0to63(rhs),bits64to127(0) {}
....


/Peter
 
R

Rob Williscroft

Richard Cavell wrote in in
comp.lang.c++:
#include <stdint.h>

class uint128bit { public:
uint64_t bits0to63; uint64_t bits64to127;

uint128bit operator= (uint128bit op2) { bits0to63 = op2.bits0to63;
bits64to127 = op2.bits64to127; return *this; }
uint128bit operator= (uint64_t op2) { bits0to63 = op2; bits64to127
= 0; return *this; } };

int main (int argc, char * const argv[]) {
uint64_t a = 1LL;

This is an initialization *not* an assignment, as it isn't an
assignment it doesn't use the assignment operator (operator = ()).
uint128bit i128_a = a;
return 0;
}

This last line of code fails, saying: conversion from 'uint64_t' to
non-scalar type 'uint128bit' requested. What have I done wrong?

You haven't provided a converting constructor.

uint128bit( uint64_t a ) { *this = a; }

you will need:

uint128bit() {}

too, as the user defined constructor suppresses the compiler
generated default constructor.

In case you don't know, <stdint.h> isn't C++ (its C) so your
code isn't Standard (portable) C++.

HTH.

Rob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top