gpt4 book ai didi

c++ - 如何使 '=' 重载在 '=' 的另一端工作

转载 作者:行者123 更新时间:2023-12-01 14:29:29 25 4
gpt4 key购买 nike

我已经将这个小的 C++ 程序作为我家庭作业的一部分。我不允许更改主要内容。我成功了

board1[{1, 1}] = 'X';

但现在我做不到

char c = board1[{1, 2}];

我知道它不起作用,因为 c 是 char 类型,我正在向它返回“CellValue”。但我不明白如何使“=”以另一种方式工作并使其返回值作为 char当我希望它位于“=”的右侧时。整个代码:


#include <iostream>
using namespace std;

class CellValue {
public:
char value;

void operator=(char charToAdd) {
if (charToAdd == 'X' || charToAdd == 'O' || charToAdd == '.') {
value = charToAdd;;
}
else {
cout << "ERROR!" << endl;
}
}

friend ostream& operator<<(ostream& os, const CellValue &CellToPrint) { //prints matrix
cout << CellToPrint.value << endl;
os << CellToPrint.value;
os << endl;
return os;
}
};

class Cell
{
public:
int row; int col;
};


class Board {
private:
int size;
CellValue** matrix = nullptr;

public:

Board(int sizeToSet) { //constructor with size
size = sizeToSet;

matrix = new CellValue*[size]; //creates a matrix
for (int i = 0; i < size; i++)
matrix[i] = new CellValue[size];

for (int i = 0; i < size; i++) { //makes every cell in matix '.'
for (int j = 0; j < size; j++) {
matrix[i][j].value = '.';
}
}
}




~Board() { //destructor
for (int i = 0; i < size; i++)
delete[] matrix[i];
delete[] matrix;
}





CellValue& operator[](const Cell& cellToChange) {
if (cellToChange.row < size && cellToChange.col < size) {
return { matrix[cellToChange.row][cellToChange.col] };
}
else
cout << "ERROR!" << endl;
}


};


int main() {
Board board1{ 4 }; // Initializes a 4x4 board
board1[{1, 1}] = 'X';
board1[{1, 2}] = 't';
cout << board1[{1, 1}] << endl;
cout << board1[{1, 2}] << endl;
char c = board1[{1, 2}];


return 0;
}

我刚开始用 C++ 编程,所以我现在可以使用一些太聪明的东西了。我想从你那里得到一些帮助。谢谢!

最佳答案

如果您的类的实例是赋值的右侧,而左侧不是同一类型,则必须提供用户定义的转换才能使其工作。

有两种方法可以处理赋值。第一个是左侧对象可以提供一个赋值运算符或转换构造函数,它采用右侧类型的对象。这是您使用 CellValue::operator=() 所做的,但当 LHS 为 char 时无法工作,因为您无法修改内置类型。

第二种方式是右边的对象提供了一个转换运算符到左边的类型(或者其他可以赋值给它的东西)。这是通过将 operator char() 添加到您的 CellValue 类来完成的:

class CellValue{
public:
operator char() const{
return value;
}
// rest as before
};

这可以是一个 const 成员函数,因为它只读取数据。

关于c++ - 如何使 '=' 重载在 '=' 的另一端工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59273707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com