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!阅读原文】。感谢您的支持!


C#总结(六)EventBus事件总线的使用-自己实现事件总线... 在C#中,我们可以在一个类中定义自己的事件,而其他的类可以订阅该事件,当某些事情发生时,可以通知到该类。这对于桌面应用或者独立的windows服务来说是非常有用的。但对于一个web应用来说是有点问题的,因为对象都是在web请求中创建的,而且...
Checking the translation of C ++... I am translating some C++ code to ObjectPascal (first time), and C++ is still fairly new to me. The C++ header file...
Modern SAT solvers: fast, neat and underused (part... Before I started doing research for Intelligent Data Analysis (IDA) group at FEE CTU , I saw SAT solvers as academicall...
高并发、低延迟之玩转CPU高速缓存(附C#示例)... 写在前面 好久没有写博客了,一直在不断地探索响应式DDD,有get到了很多新知识,解惑了很多老问题,最近读了Martin Fowler大师一篇非常精彩的博客 The LMAX Architecture ,里面有一个术语Mechanic...
LeeCode数组第15题三数之和 题目:三数之和 内容: 给定一个包含 n 个整数 的数组 nums ,判断 nums 中是否存在三个元素 a,b, c , 使得 a...