Форум программистов, компьютерный форум CyberForum.ru
Наши страницы

Ключ доступа protected - C++

Войти
Регистрация
Восстановить пароль
Другие темы раздела
C++ lib библиотеки http://www.cyberforum.ru/cpp-beginners/thread45710.html
Я пишу статическую библиотеку, и в неё мне надо подключить другие стат. либы (из DirectX SDK). Как их подключить? Пробовал через #pragma comment(lib, "имя библиотеки"), но когда в другом проекте я...
C++ текст на русском! Что неправильного в тексте программы? нужнго слово ПРИВЕТ вывести на экран! // rus.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <windows.h> char *... http://www.cyberforum.ru/cpp-beginners/thread45698.html
C++ Error LNK2001: неразрешенный внешний символ
Помогите пожалуйста тупому нубу :) Все неприятности начались после добавления дружественного класса - class KWnd { static HWND mhWnd; WNDCLASS wc; static HINSTANCE hInstance; static...
не работает функция isupper() C++
Доброе утро!У меня в программе не работает функция isupper(): for(int index = 0; index < strlen(str); index++) { if(isupper(*(str+index))) count_symbol++; } При компиляции все...
C++ текстовая обработка http://www.cyberforum.ru/cpp-beginners/thread45658.html
дано задание: "Дана последовательность строк. Каждая строка состоит из слов, разделенных пробелами. Написать программу, обеспечивающую ввод строк и их корректировку. Корректировка заключается в...
C++ Переопределение оператора== Создал функцию-операцию == для экземпляров класса, однако при выполнении данного кода Trigger.h #pragma once #include "combinate.h" class Trigger : public Combinate { static int... подробнее

Показать сообщение отдельно
zim22
depict1
276 / 141 / 2
Регистрация: 11.07.2009
Сообщений: 606
01.08.2009, 09:49
Цитата Сообщение от M128K145 Посмотреть сообщение
Protected - это уже не public, но еще и не private, со всеми вытекающими из этого последствиями
вытекающие последствия самому додумывать?
***
C++ Primer, Fourth Edition
15.2.2. protected Members
The protected access label can be thought of as a blend of private and public:

Like private members, protected members are inaccessible to users of the class.

Like public members, the protected members are accessible to classes derived from this class.

In addition, protected has another important property:

A derived object may access the protected members of its base class only through a derived object. The derived class has no special access to the protected members of base type objects.

As an example, let's assume that Bulk_item defines a member function that takes a reference to a Bulk_item object and a reference to an Item_base object. This function may access the protected members of its own object as well as those of its Bulk_item parameter. However, it has no special access to the protected members in its Item_base parameter:

void Bulk_item::memfcn(const Bulk_item &d, const Item_base &b)
{
// attempt to use protected member
double ret = price; // ok: uses this->price
ret = d.price; // ok: uses price from a Bulk_item object
ret = b.price; // error: no access to price from an Item_base
}



The use of d.price is okay, because the reference to price is through an object of type Bulk_item. The use of b.price is illegal because Bulk_item has no special access to objects of type Item_base
Key Concept: Class Design and Protected Members
In the absence of inheritance, a class has two kinds of users: members of the class itself and the users of that class. This separation between kinds of users is reflected in the division of the class into private and public access levels. Users may access only the public interface; class members and friends may access both the public and private members.

Under inheritance, there is now a third kind of user of a class: programmers who will define new classes that are derived from the class. The provider of a derived class often (but not always) needs access to the (ordinarily private) base-class implementation. To allow that access while still preventing general access to the implementation, an additional access label, protected, is provided. The data and function members in a protected section of a class remain inaccessible to the general program, yet are accessible to the derived class. Anything placed within a private section of the base class is accessible only to the class itself and its friends. The private members are not accessible to the derived classes.

When designing a class to serve as a base class, the criteria for designating a member as public do not change: It is still the case that interface functions should be public and data generally should not be public. A class designed to be inherited from must decide which parts of the implementation to declare as protected and which should be private. A member should be made private if we wish to prevent subsequently derived classes from having access to that member. A member should be made protected if it provides an operation or data that a derived class will need to use in its implementation. In other words, the interface to the derived type is the combination of both the protected and public members.
1
 
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin® Version 3.8.9
Copyright ©2000 - 2017, vBulletin Solutions, Inc.
Рейтинг@Mail.ru