2017-11-19 3 views
0

私がしたいことの本質は、Vector2Dの2つのインスタンスを取得し、3番目のインスタンスに戻して作成する3番目のベクトルを作成することです。私が直面している問題は、そうすることにどのように進むべきかについて全面的にはわからないということです。そのようなものがあれば、インスタンスの送信の構文を見つけようとしましたが、私の書籍の中で有用なものを見つけることはできませんでした。2つのArrayインスタンスの合計を作成する

#include<iostream> 
#include<string> 
#include<array> 
using namespace std; 

class vector2D 
{ 
    public: 
     array<float, 2> get() 
     { 
      return xy_coord; 
     } 

     void set(float x, float y) 
     { 
      xy_coord[0] = x; 
      xy_coord[1] = y; 
     } 

     array<float, 2> vectorAdd(a, b) 
     { 
      array<float, 2> c; 
      for (int i = 0; i < 2; i++) 
      { 
       c[i] = a[i] + b[i]; 
      } 

      return c; 
     } 

    private: 
     array<float, 2> xy_coord; 
}; 

int main() 
{ 
    string y; 
    vector2D a, b, c; 
    array<float, 2> temp; 
    a.set(2.0, 3.0); 
    b.set(4.0, 5.0); 
    temp = c.vectorAdd(a, b); 
    c.set(temp[0], temp[1]); 

    getline(cin, y); 
} 

アイデアはvectorAddにインスタンスAおよびBに送信し、それらを合計することで、その後、(私は(メインでコードを書くためのより良い方法があると確信して返された値に等しいCを設定します)、しかし私はどのようにわからない)。要するに、この作業を行うためには、aとbを何とか定義する必要があります。

+1

オペレータでC++クラスを使用できるようにすることができます。たとえば、「a + b」に意味があるとします。 https://en.wikipedia.org/wiki/Operator_overloading#Examplesをご覧ください – Treeston

答えて

0

たぶん、あなたはあなたの周りの配列を渡す必要はありませんので、代わりにこのような何かを行うことができます:

#include <iostream> 

class Vector2D 
{ 
private: 

    double _x; 
    double _y; 

public: 

    Vector2D() = delete; 
    Vector2D(double x, double y) : _x(x), _y(y) {} 
    double X() const { return _x; } 
    double Y() const { return _y; } 
    Vector2D operator+(Vector2D const &v) const 
    { 
     return Vector2D(X() + v.X(), Y() + v.Y()); 
    } 

}; 

int main() 
{ 
    Vector2D v1(10.0, 20.0); 
    Vector2D v2(100.0, 200.0); 
    Vector2D v3 = v1 + v2; 

    std::cout << v3.X() << " " << v3.Y(); 

    return 0; 
} 

プリント:

110 220 
0
Do you need to use array<float, 2>? Have you thought of using pair<float, float>? 

A lot (all?) of the operations that you have in your Vector2D class come for free with Pair<>. 

を次に、あなただけの他の人とオペレータ+を作成します提案している。

#include <iostream> 
#include <utility> 

using namespace std; 

using Coord = pair<float, float>; 

template <typename L, typename R> 
Coord operator+(const L& x, const R& y) { return std::make_pair(x.first + y.first, x.second + y.second); } 

int main() 
{ 

    Coord a { 5.0f, 6.0f }; 
    Coord b { 7.0f, 9.0f }; 
    Coord c = a + b; 

    std::cout.precision(5); 
    std::cout << "c= (" << std::fixed << c.first << ", " << c.second << ")" << std::endl; 

    return 0; 
} 
関連する問題