gpt4 book ai didi

c++ - 如何显示类中的坐标?

转载 作者:行者123 更新时间:2023-11-30 01:12:12 25 4
gpt4 key购买 nike

我在显示读入类的坐标时遇到问题。这是我第一次使用类(class),所以请理解!这是我目前所拥有的:

#include <iostream>

using namespace std;

class Vector{
private:
float x;
float y;
public:
Vector(float f1, float f2)
{
x=f1;
y=f2;
}

Vector(){}

float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}


};

int main()
{
Vector v1(0.5, 0.5);

cout << "v1 ";
v1.display();
system("pause");
return 0;
}

打印

v1 (-1.07374e+008,-1.07374e+008)

最佳答案

您的问题是您没有打印出在 main() 中创建的 Vector 的坐标,而是打印出函数中默认创建的坐标。而不是

float display()
{
Vector v;
cout << "(" << v.x << "," << v.y << ")" << endl;
return 0;
}

你需要

float display()
{
//Vector v; remove this
cout << "(" << x << "," << y << ")" << endl;
// no v.x no v.y
return 0;
}

我建议您将默认构造函数更改为

Vector() : x(0), y(0) {}

所以它会打印

v1 (0,0)

你也应该改变

Vector(float f1, float f2)
{
x=f1;
y=f2;
}

Vector(float f1, float f2) : x(f1), y(f2) {}

因为养成是个好习惯。在处理非 POD 类型时,这可以节省资源和 CPU 周期。有关详细信息,请参阅 Why should I prefer to use member initialization list?

关于c++ - 如何显示类中的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34635663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com