Overloading unary operator~

I am stuck with this unary operator~ overloading part. This is my code:

Header

#ifndef NYBLE_H
#define NYBLE_H

class Nyble
{
public:
    // insert your code here
    Nyble()=default;
    Nyble(const Nyble& n);
    Nyble& operator=(const Nyble& n);
    explicit Nyble(unsigned char d);
    ~Nyble();
    Nyble operator~(const Nyble& rhs) const;
    unsigned char getData();

private:
    // Do not change this data
    unsigned char data;

};

Source

 Nyble Nyble::operator~(const Nyble&rhs) const
    {
        char unsigned temp=rhs.data
        temp= static_cast<unsigned char>(~temp);
        return Nyble(temp);
    }

Is this correct? If not, what is the correct form?


Solution 1:

You almost had it. Just don't use any parameter for your operator~ method. Also, implementation is a half-liner, as you can directly construct and return an object using ~data as an argument. A possible implementation and test:

[Demo]

#include <iostream>  // cout
#include <ostream>

class Nyble {
public:
    explicit Nyble(unsigned char d) : data{d} {}
    
    Nyble operator~() const { return Nyble{static_cast<unsigned char>(~data)}; }
    
    unsigned char getData() const { return data; }
private:
    unsigned char data;
};

std::ostream& operator<<(std::ostream& os, const Nyble& n)
{
    return os << "0x" << std::hex << static_cast<int>(n.getData());
}

int main() {
    for (unsigned short us{0}; us <= static_cast<unsigned char>(~0); ++us)
    {
        Nyble n{static_cast<unsigned char>(us)};

        std::cout << "n = " << n << ", ~n = " << ~n << "\n";
    }
}

// Outputs:
//
//   n = 0x0, ~n = 0xff
//   n = 0x1, ~n = 0xfe
//   n = 0x2, ~n = 0xfd
//   n = 0x3, ~n = 0xfc
//   ...