面试题答案
一键面试-
运算符重载方式选择:
- 成员函数:
- 适用于一元运算符(如
++
、--
)和具有天然所有者关系的二元运算符。例如,对于矩阵类Matrix
,如果我们将矩阵加法+
重载为成员函数,那么调用者(左操作数)就是矩阵对象本身。这种方式符合 “对象调用成员函数” 的自然逻辑,而且成员函数可以直接访问对象的私有成员。例如,对于矩阵的+=
运算符重载,将其定义为成员函数是很合适的,因为它是对调用者对象自身进行修改。
- 适用于一元运算符(如
- 友元函数:
- 当运算符的左操作数不是本类对象时,友元函数比较有用。比如,如果我们想实现矩阵与标量的乘法,如
Matrix operator*(double scalar, const Matrix& m)
,标量scalar
不能调用Matrix
的成员函数(因为标量不是Matrix
类型),此时将这个乘法运算符重载为友元函数可以解决这个问题。同时,友元函数也可以访问类的私有成员。
- 当运算符的左操作数不是本类对象时,友元函数比较有用。比如,如果我们想实现矩阵与标量的乘法,如
- 普通函数:
- 普通函数不具有访问类私有成员的特权,除非类将其声明为友元。在实现一些不需要访问类私有成员的通用操作时,可以使用普通函数。例如,如果矩阵类有一个简单的打印函数
printMatrix(const Matrix& m)
,这个函数不需要修改矩阵的私有数据,就可以定义为普通函数。
- 普通函数不具有访问类私有成员的特权,除非类将其声明为友元。在实现一些不需要访问类私有成员的通用操作时,可以使用普通函数。例如,如果矩阵类有一个简单的打印函数
- 成员函数:
-
加法运算符重载的代码实现(假设矩阵存储在二维数组中):
#include <iostream>
#include <vector>
class Matrix {
private:
std::vector<std::vector<double>> data;
int rows;
int cols;
public:
Matrix(int r, int c) : rows(r), cols(c) {
data.resize(rows, std::vector<double>(cols, 0));
}
// 重载加法运算符为成员函数
Matrix operator+(const Matrix& other) const {
if (rows != other.rows || cols != other.cols) {
throw std::invalid_argument("Matrices must have the same dimensions for addition.");
}
Matrix result(rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result.data[i][j] = data[i][j] + other.data[i][j];
}
}
return result;
}
// 用于设置矩阵元素值
void setElement(int i, int j, double value) {
if (i >= 0 && i < rows && j >= 0 && j < cols) {
data[i][j] = value;
} else {
throw std::out_of_range("Index out of range.");
}
}
// 用于获取矩阵元素值
double getElement(int i, int j) const {
if (i >= 0 && i < rows && j >= 0 && j < cols) {
return data[i][j];
} else {
throw std::out_of_range("Index out of range.");
}
}
};
int main() {
Matrix m1(2, 2);
Matrix m2(2, 2);
m1.setElement(0, 0, 1.0);
m1.setElement(0, 1, 2.0);
m1.setElement(1, 0, 3.0);
m1.setElement(1, 1, 4.0);
m2.setElement(0, 0, 5.0);
m2.setElement(0, 1, 6.0);
m2.setElement(1, 0, 7.0);
m2.setElement(1, 1, 8.0);
Matrix sum = m1 + m2;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
std::cout << sum.getElement(i, j) << " ";
}
std::cout << std::endl;
}
return 0;
}