Questions about overloading C ++ operators

综合编程 2018-06-20

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!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Quick Q: Undefined behavior and sequence points Quick A: No quick A. Recently on SO: Undefined behavior and s...
15.C++-操作符重载 首先回忆下以前学的函数重载 函数重载 函数重载的本质为 相互独立的不同函数 通过 函数名 和 函数参数 来确定函数调用 ...
Main 方法 一个c# 程序有且只有一个静态的Main函数,命名空间首字母一般大写 namespace Test02 { class Program { ...
Why not have a zero exception if the variable is n... This is the code: using System; using System.Collections.Generic; using System...
C++11 及之上的一些新东西 读代码的时候遇到了一些新东西,以前从没见过的语句和使用方式,惊觉 C++ 标准都扩展到 C++17 了,然而我以前写 ACM 的时候甚至连 STL 都很少用。 ...