Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Lect03

.pdf
Скачиваний:
5
Добавлен:
06.02.2016
Размер:
630.29 Кб
Скачать

3. Динамическоесоздание объектов.Конструктор копирования.inline-методы.

«Объектно-ориентированное программирование»

доцентПриваловМ.В.

Донецк,ДонНТУ,2011

Динамическоеразмещение объектоввпамяти

Операторы new и delete.

<pointer_to_name> = new <name> [<size>];

...

delete <pointer_to_name>;

Создание экземпляров классов с использованием указателей.

int main() { clrscr();

cout << "Program beginning" << endl; DoubleVector *vector;

cout << "Constructor is not called until memory is not allocated"<<endl;

vector = new DoubleVector;

cout << "Vector length is " << vector->GetLength() << endl; vector->SetLength(100);

cout << "Vector length is " << vector->GetLength() << endl; cout << "Object will be destroyed" << endl;

delete vector; printf("Program end\n"); return 0;

}

Результатыработы

Program beginning

Constructor is not called until memory is not allocated

Created!

Vector length is 0

Vector length is 100

Object will be destroyed

Destroyed!

Program end

Динамическиемассивыобъектов

<class_type_ptr> = new <class_type>[<size>];...

delete []<class_type_ptr>;

^^^^ <--- Важно!!

int main()

{

cout << "Program beginning" << endl;

DoubleVector *vector = new DoubleVector[5];

// Неправильно!! delete vector;

cout << "Program end" << endl; return 0;

}

Результаты

Program beginning

Created!

Created!

Created!

Created!

Created!

Destroyed!

Program end

Исправленныйпример

int main()

{

clrscr();

cout <<"Program beginning"<<endl; DoubleVector *vector;

vector = new DoubleVector[5];

// Правильно. delete []vector;

cout<<"Program end\n“<<endl; return 0;

}

Результаты

Program beginning

Created!

Created!

Created!

Created!

Created!

Destroyed!

Destroyed!

Destroyed!

Destroyed!

Destroyed!

Program end

Доступкполямиметодам

class test { public:

test() {} ~test() {} int a;

private: int b;

protected: int c;

};

class test_child : public test { public:

int d; test_child() {} ~test_child() {} my_method();

};

Доступкполямиметодам

test_child::my_method() {

//OK d = 3; c = 7;

//Ошибка!! b = 1;

}

int main() { test x; test_child y;

// OK x.a = 5; y.d = 10;

// Ошибки! x.b = 1; x.c = 2; y.c = 3;

return 0;

}

Использованиессылок

тип&идентификатор= идентификатор;

или

функция(тип&идентификатор);

Ссылкавтороеимяобъекта. Ссылканеуказатель!

Ссылкадолжнабытьинициализирована

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]