我在寫一個程序,詢問用戶兩個向量(帶有力和大小),然後返回兩個向量的和。我並不是真的在找人給我一些代碼,但我真的需要一些關於如何繼續的指導。我覺得我真的不明白類/構造函數的實現,所以我很確定我正在做的事情不正確,或者至少效率低下。注意:我希望這很明顯,我沒有完成。我只是有樣的「編碼器的塊」的:P使用類/構造函數的指導
#include "std_lib_facilities_4.h"
class Physics_vector {
double force, magnitude, x, y, f, m;
vector<double> final;
vector<double> v;
public:
Physics_vector(double x, double y) :force(x), magnitude(y) {};
void set_vector(double f, double m);
int get_vector(vector<double> final);
double add_physics_vector();
};
void Physics_vector::set_vector(double f, double m)
{
f = force;
m = magnitude;
vector<double> final;
final.push_back(f);
final.push_back(m);
}
int Physics_vector::get_vector(vector<double> final)
{
for (int i = 0; i < 2; ++i) {
cout << final[i] << '\n';
}
return 0;
}
int main()
{
cout << "Howdy!" << '\n';
cout << "This program adds together two vectors."
<< endl;
cout << "First, enter in the force and magnitude of your first vector."
<< "\nExample: 4 7." << endl;
double user_force, user_magnitude, force, magnitude;
cin >> user_force >> user_magnitude;
Physics_vector first(user_force, user_magnitude);
first.set_vector(force, magnitude);
cout << "Next, enter in the force and magnitude of your second vector."
<< endl;
cin >> user_force >> user_magnitude;
Physics_vector second(user_force, user_magnitude);
}
編輯:好吧,讓我改變了我的代碼一點,使它更清潔(如果它不告訴我)。但現在我的問題是函數調用。
class Physics_vector {
public:
Physics_vector(double x = 0, double y = 0) :x(x), y(y) {}
double get_vector(double x, double y);
private:
double x, y;
};
double Physics_vector::get_vector(double x, double y)
{
return x;
return y;
}
double add_physics_vector(vector<double> vect_1, vector<double> vect_2)
{
return 0.0;
}
int main()
{
cout << "Howdy! Please enter your first vector (direction and magnitude) ."
<< "\nExample: 1 2." << endl;
double user_direction = 0;
double user_magnitude = 0;
cin >> user_direction >> user_magnitude;
Physics_vector(user_direction, user_magnitude);
//get_vector(...aaaand I'm stuck...
}
如何獲得get_vector(double x, double y)
使用x
和y
值從Physics_vector()
,因爲它的參數呢?我相信這對你們中的大多數人來說似乎是非常基本的。我討厭我在課上遇到這麼多麻煩...
在此先感謝。
你可能不應該離開構造私有。 – jaho
@Marian謝謝你指出。使它成爲'public'可能會幫助:) –