:)我目前正在编写类的练习练习,在测试代码时遇到了一个问题:输入似乎没有正常工作,因为无论我输入什么向量,输出总是返回(有符号,如果我乘以负数)零向量。任何帮助将非常感谢!谢谢:)(也许我很迟钝,但我没看到问题在哪里
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Vector {
private:
double x, y, z; // Coordinates
double scalar;
public:
Vector(double x1, double y1, double z1) {
x=x1; y=y1; z=z1;
}
Vector operator+ (Vector a) {
x += a.x;
y += a.y;
z += a.z;
return *this;
}
friend Vector operator* (Vector a, double scalar) {
a.x *= scalar;
a.y *= scalar;
a.z *= scalar;
return a;
}
friend Vector operator* (double scalar, Vector a) {
a.x *= scalar;
a.y *= scalar;
a.z *= scalar;
return a;
}
friend std::ostream& operator<< (std::ostream& o, Vector a) {
o << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return o;
}
friend std::istream& operator>> (std::istream& i, Vector a) {
char c;
i >> c >> a.x >> c >> a.y >> c >> a.z >> c;
return i;
}
double get(char i) const {
if (i=='x') return x;
if (i=='y') return y;
if (i=='z') return z;
}
};
答案 0 :(得分:2)
我认为你operator>>
中的问题。您应该像Vector
那样传递friend std::istream& operator>> (std::istream& i, Vector& a)
// ^
的引用:
a
否则operator+
是一个局部变量,它不会改变。
顺便说一下。您的+=
作为Vector
。它应该创建新的{{1}}。
答案 1 :(得分:0)
我重构了你的程序以满足你的需要。尽管如此,还有很多优化的空间。
#include <iostream>
#include <sstream>
#include <string>
class Vector
{
private:
double x, y, z; // Coordinates
public:
Vector() : x(0), y(0), z(0) {}
Vector(double x1, double y1, double z1) : x(x1), y(y1), z(z1) {}
Vector operator+ (Vector const & rhs) const {
return Vector(this->x + rhs.x, this->y + rhs.y, this->z + rhs.z);
}
friend Vector operator* (Vector const & lhs, double s) {
return Vector(lhs.x * s, lhs.y * s, lhs.z * s);
}
friend Vector operator* (double s, Vector const & rhs) {
return Vector(rhs.x * s, rhs.y * s, rhs.z * s);
}
friend std::ostream& operator<< (std::ostream & os, Vector const & a) {
os << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return os;
}
friend std::istream& operator>> (std::istream & is, Vector & a) { // This needs to be a &, to be modified
char c; // To dump extra characters
is >> c >> a.x >> c >> a.y >> c >> a.z >> c;
return is;
}
double get(char i) const {
switch (i)
{
case 'x' : return x;
case 'y' : return y;
case 'z' : return z;
default : throw std::runtime_error("Vector doesn't contain specified character");
}
}
};
int main()
{
Vector v1 = Vector(2.3, 3.5, 4.7); std::cout << v1 << std::endl;
Vector v2 = Vector(1.4, 6.7, 1.1); std::cout << v2 << std::endl;
Vector v3 = v1 + v2; std::cout << v3 << std::endl;
Vector v4 = 3 * v1; std::cout << v4 << std::endl;
Vector v5 = v2 * 5; std::cout << v5 << std::endl;
std::cout << v5.get('x') << std::endl;
std::stringstream ss; ss << "(1,2,3)";
Vector v6; std::cout << v6 << std::endl;
ss >> v6; std::cout << v6 << std::endl;
Vector v7 = 3 * v6; std::cout << v7 << std::endl;
}
输出 -
$ g++ vector.cpp -o vector && ./vector
(2.3, 3.5, 4.7)
(1.4, 6.7, 1.1)
(3.7, 10.2, 5.8)
(6.9, 10.5, 14.1)
(7, 33.5, 5.5)
7
(0, 0, 0)
(1, 2, 3)
(3, 6, 9)
嗯,请仔细检查。如果您需要更多解释,我很乐意提供帮助。