class Vector3 { public: Vector3(); Vector3(double x,double y,double z); public: Vector3 operator+(const Vector3 &A)const; Vector3 operator++(); friend Vector3 operator-(const Vector3 &v1, const Vector3 &v2); friend Vector3 operator--(Vector3 &v); void display()const; private: double m_x; double m_y; double m_z; }; Vector3::Vector3() :m_x(0.0), m_y(0.0), m_z(0.0) {} Vector3::Vector3(double x, double y,double z) : m_x(x), m_y(y), m_z(z) {} //运算符重载 Vector3 Vector3::operator+(const Vector3 &A) const { Vector3 B; B.m_x = this->m_x + A.m_x; B.m_y = this->m_y + A.m_y; B.m_z = this->m_z + A.m_z; return B; } Vector3 Vector3::operator++() { this->m_x ++; this->m_y ++; this->m_z ++; return *this; } void Vector3::display()const { cout<<"(" << m_x << "," << m_y << "," << m_z << ")" << endl; } Vector3 operator-(const Vector3 &v1,const Vector3 &v2) { Vector3 B(v1.m_x - v2.m_x, v1.m_y - v2.m_y, v1.m_z - v2.m_z); return B; } Vector3 operator--( Vector3 &v) { v.m_x--; v.m_y--; v.m_z --; return v; } int main() { Vector3 v1(1, 2, 3); Vector3 v2(2, 3, 2); ++v1;//v1.operator++(); 作为类成员函数可以显式调用 v1.display(); --v2; v2.display(); Vector3 v3 = v1 + v2;// v1.operator+(v2);作为类成员函数可以显式调用 v3.display(); Vector3 v4 = v1 - v2; v4.display(); return 0; }分析一下这段代码,可以将两个友元函数改为类成员函数吗?
时间: 2024-03-01 12:49:44 浏览: 81
可以将两个友元函数改为类成员函数,具体实现如下:
```c++
class Vector3 {
public:
Vector3();
Vector3(double x,double y,double z);
Vector3 operator+(const Vector3 &A)const;
Vector3 operator++();
Vector3 operator--();
Vector3 operator-(const Vector3 &A) const;
void display() const;
private:
double m_x;
double m_y;
double m_z;
};
Vector3 Vector3::operator+(const Vector3 &A) const {
Vector3 B;
B.m_x = this->m_x + A.m_x;
B.m_y = this->m_y + A.m_y;
B.m_z = this->m_z + A.m_z;
return B;
}
Vector3 Vector3::operator++() {
this->m_x ++;
this->m_y ++;
this->m_z ++;
return *this;
}
Vector3 Vector3::operator--() {
this->m_x --;
this->m_y --;
this->m_z --;
return *this;
}
Vector3 Vector3::operator-(const Vector3 &A) const {
Vector3 B;
B.m_x = this->m_x - A.m_x;
B.m_y = this->m_y - A.m_y;
B.m_z = this->m_z - A.m_z;
return B;
}
void Vector3::display() const {
cout << "(" << m_x << "," << m_y << "," << m_z << ")" << endl;
}
```
其中,将 `operator-` 和 `operator--` 改为了成员函数,并且将 `operator-` 的参数名改为了 `A`,来避免与 `operator--` 的参数名冲突。
阅读全文