我正在学习向量,我想创建一个名为“createVector2D”的函数,所以我有这个代码:
#include <iostream>
#include <vector>
#include <math.h>
using namespace std;
class Vector2D {
public:
float x, y;
Vector2D(float X, float Y)
{
x = X;
y = Y;
}
float getMagnitude()
{
return sqrt((x * x) + (y * y));
}
};
void createVector (float x, float y, string vectorname){
Vector2D vectorname(x,y);
cout<<"Vector created!\nName: "<<vectorname<<"\nx: "<<x<<"\ny:"<<y<<endl;
}
int main(){
float x;
float y;
string vecname;
printf ("Vector Velocidad (x,y)\nInserta X\n");
cin>>x;
system("cls");
printf ("Vector Velocidad (%f,y)\nInserta Y\n", x);
cin>>y;
system("cls");
printf ("Vector Velocidad (%f,%f)\n", x, y);
printf ("Escribe el nombre del vector\n");
cin>>vecname;
createVector (x,y,vecname);
printf ("-1. Calcular Magnitud (Modulo)\n");
printf ("-2. Enseñar Vector\n");
int op = 0;
cin>>op;
switch(op){
case 1:
cout<<vecname.getMagnitude()<<endl;
break;
case 2:
cout<<"x: "<<vecname.x<<endl;
cout<<"y: "<<vecname.y<<endl;
break;
default:
cout<<"No elegiste nada"<<endl;
break;
}
system("pause>NULL");
}
错误是字符串无法正常工作,我不知道如何将其转换为Vector2D类的Vector名称正常工作,有人知道吗? :D谢谢你的阅读。
答案 0 :(得分:0)
您希望createVector()
返回值:
Vector2D createVector(float x, float y)
{
Vector2D vec(x, y);
return vec;
}
然后将此函数的返回值分配给vecname
变量:
Vector2D vecname;
vecname = createVector(1, 2);
但是,你不需要这样的函数,因为Vector2D
已经有一个公共构造函数可以正常工作:
Vector2D vecname(1, 2);
答案 1 :(得分:0)
问题是,你做不到:
void createVector( float x, float y, string vectorname ) {
Vector2D vectorname( x, y );
cout << "Vector created!\nName: " << vectorname << "\nx: " << x << "\ny:" << y << endl;
}
vectorname
是string
变量,您尝试将其用作Vector2D
变量。
如果您希望每个实例Vector2D
都有一个名称,则需要将该数据成员添加到该类中:
class Vector2D {
public:
float x, y;
string name;
Vector2D( float X, float Y, string vectorname ) {
x = X;
y = Y;
name = vectorname;
cout << "Hello, I'm " << name << "at:\nx: " << x << "\ny: " << y << endl;
}
~Vector2D() {
cout << name << " signing off!\n";
}
float getMagnitude() {
return sqrt((x * x) + (y * y));
}
};
Vector2D createVector( float x, float y, string vectorname ) {
return new Vector2D( x, y, vectorname );
}