0

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?

rturrado
  • 7,699
  • 6
  • 42
  • 62
  • 5
    Prefix unary operators have no arguments besides the implied `this` when overloaded as member functions. That the members of the active instance played no part in your `operator ~` member implementation should be the hint that something is wonky in said-same. – WhozCraig Jan 14 '22 at 18:16
  • You should inform your instructor that `uint8_t` would be a better type than `unsigned char` for data. – Thomas Matthews Jan 14 '22 at 18:16
  • 1
    Have a look at `bitwise NOT` [here](https://en.cppreference.com/w/cpp/language/operator_arithmetic) for inside class method signature. – rturrado Jan 14 '22 at 18:22
  • 1
    [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) – Remy Lebeau Jan 15 '22 at 06:54

1 Answers1

2

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
//   ...
rturrado
  • 7,699
  • 6
  • 42
  • 62