我是C ++学习的初学者,我对'<<<<<<<&#和'>>'。 为什么cout的结果不正确?同时,输入c的坐标后,程序冻结。 代码:
class Vector
{friend istream &operator >> (istream &is,Vector &vec );
friend ostream &operator << (ostream &os,Vector &vec );
private:
int num;
double *cor;
public:
Vector(int n=0,double *c=NULL);//
};
int main()
{ double b[5]={1,2,3,4,5};
Vector a(5,b);
cout<<a;
Vector c(2);
cin>>c;
}
Vector::Vector(int n,double *c)
{
num=n;
double *cor=new double[num];
if (c) {
for (int i=0;i<n;i++) {cor[i]=c[i];cout<<cor[i]<<endl;}
}
}
istream &operator >> (istream &is,Vector &vec )
{ cout<<"Input the coordinate:";
for (int i=0;i<vec.num;i++)
is>>vec.cor[i];
return is;
}
ostream &operator << (ostream &os,Vector &vec )
{
for (int i=0;i<vec.num;i++){
os<<vec.cor[i];}
return os;
}
答案 0 :(得分:1)
double *cor=new double[num];
您正在声明名为cor
的本地变量,而不是初始化成员cor
。它应该是:
cor = new double[num];
但是在实际代码中,您会使用unique_ptr
到double
数组,delete
自动生成数组(没有额外开销):
#include <iostream>
#include <memory> // for unique_ptr
using namespace std;
class Vector {
public:
Vector(int = 0, double* = nullptr);
private:
friend istream& operator>>(istream&, Vector& vec);
friend ostream& operator<<(ostream&, Vector& vec);
int num;
unique_ptr<double[]> array;
};
int main() {
double b[] = {1, 2, 3, 4, 5};
Vector a(5, b);
cout << a;
Vector c(2);
cin >> c;
}
Vector::Vector(int n, double* c) {
num = n;
array = make_unique<double[]>(n); // in C++14
//array = unique_ptr<double[]>(new double[n]); // in C++11
if (!c) return;
for (int i = 0; i < n; i++) {
array[i] = c[i];
cout << array[i] << endl;
}
}
istream& operator>>(istream& is, Vector& vec) {
cout << "Input the coordinates: ";
for (int i = 0; i < vec.num; i++)
is >> vec.array[i];
return is;
}
ostream& operator<<(ostream& os, Vector& vec) {
for (int i = 0; i < vec.num; i++)
os << vec.array[i];
return os;
}
答案 1 :(得分:0)
小而重要的提示: 使用'const':
> ostream &operator << (ostream &os,const Vector &vec)
因为vec是通过引用收到的,你不会改变它。