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 );
    int num;
    double *cor;
    Vector(int n=0,double *c=NULL);//
int main()
{   double b[5]={1,2,3,4,5};
    Vector a(5,b);
Vector::Vector(int n,double *c)
    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++){
    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

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

#include  // for unique_ptr

using namespace std;

class Vector {
    Vector(int = 0, double* = nullptr);

    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;

责编内容by:Hello, buddy!阅读原文】。感谢您的支持!


Oryol: System Design Philosophy I think I have written (and re-written, and re-re-written) enough different Oryol modules now that a pattern has emerged to a point where I feel comfo...
Build an MRU list that uses project settings in C# The post Build an MRU list in C# explains how to build an MRU list (most recently used list). That example stores recently used files in the ...
My Five Worst Bugs My two decades in the software industry have been rewarding, interesting, and fun. However, there has also been plenty of frustration, horrible mistak...
深度解析各种使用情境下的最佳编程语言... 在《 公司和程序员如何选择合适的编程语言? 》一文中,笔者解析了选择一种编程语言会付出哪些成本,以及依据哪些标准来选择编程语言。本文中,笔者将结合多种使用情境,解析这种情境下哪个语言才是最佳的编程语言。 Java 提起Java,C#程序员就有些坐不住了,网上有很多评论称:...
Modern C++: 7 Ways to Fake It Until You Have It Published August 31, 2018 Do you wish you had a later version of C++ in your production code? If you do, you’re not alone: a lot of C++ developers t...