Константы — различия между версиями

Материал из Deeptown Manual
Перейти к: навигация, поиск
(Константные объекты)
(minor updates)
 
Строка 54: Строка 54:
 
c.ShowStatus();        //тоже можно, метод не меняет состояния (помечен как const)
 
c.ShowStatus();        //тоже можно, метод не меняет состояния (помечен как const)
 
</source>
 
</source>
 +
 +
== 10 Keys to Happier Living ==
 +
 +
Action for Happiness has developed the 10 Keys to Happier Living based on a review of the latest scientific research relating to happiness. Everyones path to happiness is different, but the research suggests these Ten Keys consistently tend to have a positive impact on peoples overall happiness and well-being.
 +
 +
[[http://goodvillenews.com/10-Keys-to-Happier-Living-vxnwik.html 10 Keys to Happier Living]]
 +
 +
[[http://goodvillenews.com/wk.html goodville news]]
 +
 +
== Student Goes From Homeless to Harvard ==
 +
 +
Despite being abandoned to homelessness by her parents, Dawn Loggins worked as a high school custodian by day and studied hard by night to become the first person from her school to ever be admitted to Harvard.
 +
 +
[[http://goodvillenews.com/Student-Goes-From-Homeless-to-Harvard-QX9Vg4.html Student Goes From Homeless to Harvard]]
 +
 +
[[http://goodvillenews.com/wk.html goodville news]]
 +
 +
== The Opposite Of Poverty Is Justice ==
 +
 +
 +
 +
[[http://goodvillenews.com/The-Opposite-Of-Poverty-Is-Justice-oqL04K.html The Opposite Of Poverty Is Justice]]
 +
 +
[[http://goodvillenews.com/wk.html goodville news]]
 +
 +
== Rats Walking Again After Spinal Cord Injury ==
 +
 +
Scientists in Switzerland have restored full movement to rats paralyzed by spinal cord injuries in a study that spurs hope that the techniques may hold promise for someday treating people with similar injuries.
 +
 +
[[http://goodvillenews.com/Rats-Walking-Again-After-Spinal-Cord-Injury-nBLFSB.html Rats Walking Again After Spinal Cord Injury]]
 +
 +
[[http://goodvillenews.com/wk.html goodville news]]
 +
 +
== Would Gandhi Use Social Media? ==
 +
 +
If Gandhi were alive today, would he use social media? He was never anti-technology, or even anti-changing with the times. Quite the opposite, actually. If Internet technologies and social networks were around, he would certainly have embraced them -- but with a conscious mindfulness of their strengths and weaknesses.
 +
 +
[[http://goodvillenews.com/Would-Gandhi-Use-Social-Media-J39i2S.html Would Gandhi Use Social Media?]]
 +
 +
[[http://goodvillenews.com/wk.html goodville news]]

Текущая версия на 01:08, 18 июля 2012

Содержание

[править] Понятие константы

В сущности, и с точки зрения языка, константы это те же переменные объекты: их можно использовать в арифметических выражениях, передавать в качестве параметров функциям, использовать их свойства и вызывать методы. Разумеется, только те, которые не изменяют состояние самого объекта.

Объявление любой константы начинается с ключевого слова

Тип константы можно либо указать явно, как это происходит в случае константы e, либо неявно. При этом он будет назначен как тип инициализатора: константа pi будет иметь тип числа с плавающей точкой (<tt>real), а константа s — строковый тип (string).

Примечание: При объявлении констант следите за тем, чтобы их тип был ясно виден из строки объявления. Если выражение инициализатора представляет собой довольно сложное математическое выражение, либо содержит вызовы функций, лучше всего указать тип константы явно (как в примере с константой e). Иначе, это может вызывать проблемы в будущем, при работе программы или при ее отладке. В целом ситуация такая же, что и с инициализацией переменных (см. примечание).

[править] Константные объекты

Как уже было сказано выше, константами могут являться или быть объявлены любые объекты языка. Даже числа и строки, фигурирующие в программе в явном виде — тоже являются константными объектами. И их тоже можно использовать как объекты.

так можно узнать длину строки, используя свойство length:

<source lang="kpp">var len = "hello world".length();</source>

В общем случае, создать константный объект можно тем же способом что и обычную переменную-экземпляр класса: <source lang="kpp"> const myinstance = new MyClass; const myobject = MyClass.Create(); </source>

[править] Константные функции

При работе с константными объектами подразумевается, что их значение (простые объекты, вроде числовой константы) или в общем случае их состояние (экземпляр некоторого класса) не будут изменено. Чтобы указать компилятору, какие методы и операторы можно использовать, а какие нет, вводится понятие спецификатора функции. Спецификатор const, указанный в объявлении метода или оператора указывает на то, что этот метод не изменяет состояния объекта и может вызываться для констант:

<source lang="kpp"> class MyClass {

   var m_i = 0;
   public const function ShowStatus() { println(m_i); } 
   public function Check() { return i > 5; }
   function SetI(value) { m_i = value; }
   property i read m_i write SetI;

} </source>

В том случае, если где-то в коде будет создан константный экземпляр класса, то он будет допускать чтение свойства i и вызовы метода ShowStatus(), но не SetI():

<source lang="kpp"> var v = new MyClass; //создаем экземпляр-переменную const c = new MyClass; //создаем экземпляр-константу

puts('v = ' + v.i); //можно, доступ на чтение puts('c = ' + c.i); //тоже можно, чтение свойства разрешено v.i = 5; //можно, v - переменная c.i = v.i; //нельзя, c - константа, запись свойства запрещена v.Check(); //можно

c.Check(); //нельзя. метод не помечен как const

                      //(хоть и не изменяет состояния)

v.ShowStatus(); //можно c.ShowStatus(); //тоже можно, метод не меняет состояния (помечен как const) </source>

[править] 10 Keys to Happier Living

Action for Happiness has developed the 10 Keys to Happier Living based on a review of the latest scientific research relating to happiness. Everyones path to happiness is different, but the research suggests these Ten Keys consistently tend to have a positive impact on peoples overall happiness and well-being.

[10 Keys to Happier Living]

[goodville news]

[править] Student Goes From Homeless to Harvard

Despite being abandoned to homelessness by her parents, Dawn Loggins worked as a high school custodian by day and studied hard by night to become the first person from her school to ever be admitted to Harvard.

[Student Goes From Homeless to Harvard]

[goodville news]

[править] The Opposite Of Poverty Is Justice

[The Opposite Of Poverty Is Justice]

[goodville news]

[править] Rats Walking Again After Spinal Cord Injury

Scientists in Switzerland have restored full movement to rats paralyzed by spinal cord injuries in a study that spurs hope that the techniques may hold promise for someday treating people with similar injuries.

[Rats Walking Again After Spinal Cord Injury]

[goodville news]

[править] Would Gandhi Use Social Media?

If Gandhi were alive today, would he use social media? He was never anti-technology, or even anti-changing with the times. Quite the opposite, actually. If Internet technologies and social networks were around, he would certainly have embraced them -- but with a conscious mindfulness of their strengths and weaknesses.

[Would Gandhi Use Social Media?]

[goodville news]

Персональные инструменты
Пространства имён

Варианты
Действия
Навигация
информация
документация
Инструменты