Advertisement
Maplewing

6/18 C++: class Vector

Jun 17th, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.40 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. class Vector{
  6.     private:
  7.         // 資料(變數部分)
  8.         double _x; // 加底線 避免名稱上衝突
  9.         double _y;
  10.        
  11.     public:
  12.         // 方法;功能(函式部分)
  13.         friend void printVector(Vector v);
  14.        
  15.         Vector(){
  16.             _x = 0;
  17.             _y = 0;
  18.         }
  19.        
  20.         Vector(double x, double y){
  21.             _x = x;
  22.             _y = y;
  23.         }
  24.        
  25.         double length(){
  26.             return pow( _x*_x + _y*_y, 0.5 );
  27.         }
  28.        
  29.         Vector& setX(double x){
  30.             _x = x;
  31.             return *this;
  32.         }
  33.        
  34.         Vector& setY(double y){
  35.             _y = y;
  36.             return *this;
  37.         }
  38.        
  39.         double getX(){
  40.             return _x;
  41.         }
  42.        
  43.         double getY(){
  44.             return _y;
  45.         }
  46.        
  47.         void print(){
  48.             cout << "(" << _x << "," << _y << ")" << endl;
  49.         }
  50.        
  51.        
  52.         Vector operator+(const Vector& v2){
  53.             double newX = _x + v2._x;
  54.             double newY = _y + v2._y;
  55.  
  56.             Vector v3(newX, newY);
  57.             return v3;
  58.         }
  59.        
  60. };
  61.  
  62.  
  63.  
  64. int main(){
  65.     Vector v1(3, 4);
  66.     Vector v2(5, 4);
  67.    
  68.     v1.setX(5).setY(6);
  69.    
  70.     Vector v3 = v1 + v2; //v1.operator+(v2);
  71.    
  72.     v1.print();
  73.     v2.print();
  74.     v3.print();
  75.    
  76.     return 0;
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement