综合编程

Questions about overloading C ++ operators

微信扫一扫,分享到朋友圈

Questions about overloading C ++ operators
0 0

I am a beginner of C++ learning, and I have some questions about the ‘<>’. Why the results of cout are not correct? At the same time, after I input the coordinate of c, the program froze. Code:

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<>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]<> (istream &is,Vector &vec )
{   cout<<"Input the coordinate:";
    for (int i=0;i>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;
}
double *cor=new double[num];

You’re declaring a local variable named cor
, not initializing the member cor
. It should be:

cor = new double[num];

However in real code, you would use an
unique_ptr

to a double
array, which delete
s the array automatically (with no additional overhead):

#include 
#include  // 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 array;
};

int main() {
    double b[] = {1, 2, 3, 4, 5};

    Vector a(5, b);
    cout <> c;
}

Vector::Vector(int n, double* c) {
    num = n;
    array = make_unique(n); // in C++14
    //array = unique_ptr(new double[n]); // in C++11

    if (!c) return;

    for (int i = 0; i < n; i++) {
        array[i] = c[i];
        cout << array[i] <>(istream& is, Vector& vec) {
    cout << "Input the coordinates: ";
    for (int i = 0; i > 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;
}
阅读原文...

Hello, buddy!

金融行业也能用到Python?这就是Python之所以能这么火的原因吧!

上一篇

Writes a sql that returns 3 rows to a row as a list

下一篇

您也可能喜欢

评论已经被关闭。

插入图片
Questions about overloading C &plus;&plus; operators

长按储存图像,分享给朋友