`

钱能《C++程序设计教程》14章练习

阅读更多
当时学习敲的


14.3
这题还真带出问题来:临时对象的返回、参数对象自我保护的const机制。
原书的拷贝函数是没带const的,X::X(X& x) => X::X(const X& x)。
引用是很好的东西,要好好保护它,故聘请保镖const。
const还能与非const重载的……

#include <iostream>
using namespace std;

class X
{
protected:
    int y;

public:
    X(int);
    X::X(const X&); //  原来的  X::X(X&);
    ~X();
};

X::X(int y)
{
    cout << "构造:" << y << endl;
    this->y = y;
}

X::X(const X& x)    //  原来的  X::X(X& x)
{
    cout << "拷贝:" << this->y << endl;
}

X::~X()
{
    cout << "析构:" << this->y << endl;
}

X fx(X x)   //  这里隐藏了拷贝函数的调用,返回临时对象时,会调用拷贝函数
{           //  而且参数会自我保护,提升为const 
    return x;   //  关于临时对象,钱能书:14.7节 P323
}

int main(int argc, char *argv[])
{
//    X a(1);
//    X b = a;
    a = fx( X(2) );
    return 0;
}



14.2
对拷贝函数,并不用那么在意,其实就是堆上的数据一共有几份。
#include <iostream>
using namespace std;

class Vector
{
protected:
    int size;
    int* buffer;

public:
    Vector(int s = 100);
    Vector::Vector(Vector& v);
    ~Vector();

    int& Elem(int ndx);
    void Display();
    void Set();
};

Vector::Vector(int s)  // 所谓的拷贝函数
{
    size = s;
    buffer = new int[size];
    for (int i = 0; i < size; i++)
    {
        buffer[i] = i*i;
    }
}

Vector::Vector(Vector& v)
{
    size = v.size;
    buffer = new int[size];
    for (int i = 0; i < size; i++)
    {
        buffer[i] = i*i;
    }
}

Vector::~Vector()
{
    delete[]buffer;
}

int& Vector::Elem(int ndx)
{
    if (ndx < 0 || ndx >= size)
    {
        cout << "error in index" << endl;
        exit(1);
    }
    return buffer[ndx];
}

void Vector::Display()
{
    for (int i = 0; i < size; i++)
    {
        cout << buffer[i] << endl;
    }
}

void Vector::Set()
{
    for (int i = 0; i < size; i++)
    {
        buffer[i] = i + 1;
    }
}


int main(int argc, char *argv[])
{
    Vector a(5);
    a.Display();
    cout << endl;

    Vector b = a;
    a.Set();
    b.Display();

    return 0;
}




14.1
此题我主要是想体会指针对象数组,与Java的稍有不同
#include <iostream>
using namespace std;
class Samp
{
protected:
    int i;
    int j;

public:
    Samp()
    {   cout << "Constructing:" << i << endl;     }
    ~Samp()
    {   cout << "Destroying:" << i << endl;     }

public:
    void Setij(int a, int b){i = a; j = b;}
    int GetMulti(){return i*j;}
};


int main(int argc, char *argv[])
{
    Samp* p = NULL;
    p = new Samp[10];
//    Samp[] p = new Samp[10];  //  Java的做法

    if (!p)
    {
        cout << "Allocation error!" << endl;
        return -1;
    }

    for (int i = 0; i < 10; i++)
    {
        p[i].Setij(i, i);
    }

    for (int j = 0; j < 10; j++)
    {
        cout << "Multi[" << j << "]is:"
        << p[j].GetMulti() << endl;
    }

    delete[]p;  //  忘了不就很危险~

    cout << "Hello, world" << endl;
    return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics