1
Я пытаюсь использовать ~
, чтобы перевернуть биты класса «Двоичные». В этом «двоичном» классе хранится массив символов «0» и «1» с именем bs
. Я просто хочу, чтобы перевернуть символы внутри этого массива:Как перегрузить оператор ~ (побитовое)?
Binary& operator~()
{
int i = 0;
while(i < index) {
if (bs[i] == '1')
bs[i] == '0';
else bs[i] == '1';
i++;
}
return *this;
}
Но код, кажется, не в состоянии ввести петлю, независимо от того, если я использую во время или. Возможно, я написал это неправильно. Вот весь код:
#include <iostream>
#include <windows.h>
using namespace std;
TCHAR pressanykey(const TCHAR* prompt = NULL)
{
TCHAR ch;
DWORD mode;
DWORD count;
HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
// Prompt the user
if (prompt == NULL)
prompt = TEXT("Press any key to continue...");
WriteConsole(
GetStdHandle(STD_OUTPUT_HANDLE),
prompt,
lstrlen(prompt),
&count,
NULL
);
// Switch to raw mode
GetConsoleMode(hstdin, &mode);
SetConsoleMode(hstdin, 0);
// Wait for the user's response
WaitForSingleObject(hstdin, INFINITE);
// Read the (single) key pressed
ReadConsole(hstdin, &ch, 1, &count, NULL);
// Restore the console to its previous state
SetConsoleMode(hstdin, mode);
// Return the key code
return ch;
}
class Binary {
char *bs;
int index;
public:
Binary(int x) {
bs = new char[20];
index = 0;
DecimalToBinary(x);
bs[index] = '\0';
}
Binary(char* str) {
bs = str;
index = 0;
while (bs[index] != '\0') {
index += 1;
}
}
Binary(const Binary& original) {
bs = original.bs;
index = original.index;
}
~Binary() {
delete [] bs;
bs = NULL;
}
int ToDecimal() {
int result = 0;
for (int i = 0; i < index; i++) {
result *= 2;
if (bs[i] == '1')
result += 1;
}
return result;
}
Binary& operator~()
{
int i = 0;
while(i < index) {
if (bs[i] == '1')
bs[i] == '0';
else bs[i] == '1';
i++;
}
return *this;
}
Binary& operator= (const Binary &b) {
delete [] bs;
bs = NULL;
bs = b.bs;
index = b.index;
return *this;
}
void DecimalToBinary(int number) {
int remainder;
if (number == 1) {
bs[index] = '1';
index += 1;
return;
}
if (number == 0) {
bs[index] = '0';
index += 1;
return;
}
remainder = number%2;
DecimalToBinary(number >> 1);
if (remainder == 1) {
bs[index] = '1';
index += 1;
return;
}
if (remainder == 0) {
bs[index] = '0';
index += 1;
return;
}
}
friend istream& operator>>(istream& is, Binary& b);
friend ostream& operator<<(ostream& os, Binary& b);
};
istream& operator>>(istream& is, Binary& b)
{
char *str = new char[20];
is >> str;
b.bs = str;
b.index = 0;
while (b.bs[b.index] != '\0') {
b.index += 1;
}
return is;
}
ostream& operator<<(ostream& os, Binary& b)
{
os << b.bs;
return os;
}
int main() {
Binary a(15);
Binary b("10110");
Binary c(b);
cout << "binary a is " << a << endl;
cout << "binary b is " << b << endl;
cout << "binary c is " << c << endl;
cout << endl << "Re-enter binary b: ";
cin >> b;
cout << "binary a is " << a << endl;
cout << "binary b is " << b << endl;
cout << "binary c is " << c << endl;
cout << "binary b in decimal form: " << b.ToDecimal() << endl;
cout << "bit flips b: "<< ~b << endl;
pressanykey();
return 0;
}
Когда вы создаете 'Binary' с строковым литералом, вы' delete [] 'строковый литерал, вызывая' delete [] bs' в нескольких местах, который является UB. Кроме того, в 'operator =' вы 'delete [] bs', а затем присваиваете' b.bs' 'this-> bs', что заставляет два класса управлять одним и тем же ресурсом, и он дважды получает' delete [] 'ed в деструкторе. –