认证0级讲师
一般不會(a + b).area(); 這樣調用,用起來不自然。 而是會實現類似下面的一個重載函數
friend ostream &operator<<(ostream &os, const Triangle &b) { float s, area; s = (b.x + b.y + b.z) / 2; area = sqrt(s * (s - b.x) * (s - b.y) * (s - b.z)); // cout << "area is " << area << endl; os << "area is " << area <<endl; return os; }
這樣,列印的時候只要 cout 程式碼稍微改了下,具體的演算法沒看,
#include <iostream> #include <math.h> using namespace std; class Triangle { private: int x, y, z; public: Triangle() { } void area() { float s, area; s = (x + y + z) / 2; area = sqrt(s * (s - x) * (s - y) * (s - z)); cout << "area is " << area << endl; } friend ostream &operator<<(ostream &os, const Triangle &b) { float s, area; s = (b.x + b.y + b.z) / 2; area = sqrt(s * (s - b.x) * (s - b.y) * (s - b.z)); // cout << "area is " << area << endl; os << "area is " << area <<endl; return os; } friend Triangle operator+(Triangle left, Triangle right) { Triangle b; b.x = left.x + right.x; b.y = left.y + right.y; b.z = left.z + right.z; return b; } void input() { cin >> x >> y >> z; } void output() { cout << "triangle three horizon length is " << x << " " << y << " " << z << endl; } }; int main() { Triangle a, b, c; a.input(); b.input(); c.input(); (a + b).output(); // (a + b).area(); cout << a + b + c <<endl; return 0; }
PS:我更新了下,這裡其實沒必要用友元函數,直接如下用就行
Triangle operator+(Triangle other){
Triangle ret; ret.x = this->x + other.x; ret.y = this->y + other.y; ret.z = this->z + other.z; return ret;
}
你用friend來處理的話,回傳值也是一個Triangle,可以遞歸的再去加另外一個Triangle,就實現多個Triangle連加的形式
一般不會(a + b).area(); 這樣調用,用起來不自然。
而是會實現類似下面的一個重載函數
這樣,列印的時候只要 cout 程式碼稍微改了下,具體的演算法沒看,
PS:
我更新了下,這裡其實沒必要用友元函數,直接如下用就行
Triangle operator+(Triangle other)
{
}
你用friend來處理的話,回傳值也是一個Triangle,可以遞歸的再去加另外一個Triangle,就實現多個Triangle連加的形式