zoukankan      html  css  js  c++  java
  • Swift-存储属性,计算属性,类属性

    //类的属性定义
    
    class Student: NSObject {
    //    定义属性
    //    定义存储属性
        var age : Int = 0
        var name :String?
        
        var mathScore : Double = 0.0
        var chineseScore :Double = 0.0
        
    //    定义一个方法,可以是返回平均成绩 (注意: swift不建议这样使用,应该定义一个计算属性)
        func getAverageScore() -> Double {
    //        在swift如果是使用当前对象的某一个属性,或者调用当前对象的某一个方法时,可以直接使用,不用加self
            return (mathScore + chineseScore) * 0.5
        }
        
    //    定义计算属性:通过别的方式计算到结果的属性,称之为计算属性
    //    计算属性使用很多
        var averageScore :Double{
            return (mathScore + chineseScore) * 0.5
        }
        
    //    定义类属性:类属性是和整个类相关的属性,而且是通过类名直接访问
    //    一般用在单利中多点
        static var courceCount : Int = 0
        
    }
    
    //给对象属性赋值
    let stu = Student()
    stu.age = 10
    stu.name = "wj"
    
    stu.mathScore = 78
    stu.chineseScore = 70
    
    print(stu.age)
    
    if let name = stu.name{
        print(name)
    }
    
    let averageScore = (stu.mathScore + stu.chineseScore) * 0.5
    
    let ave = stu.averageScore
    
    //类属性
    //给类属性赋值
    Student.courceCount = 2
  • 相关阅读:
    hdu 1561 The more, The Better(树形dp入门)
    poj 2342 Anniversary party (树形dp入门)
    hdu 2089 不要62(数位dp入门)
    hdu 3555 Bomb (数位dp入门)
    hdu 5591 ZYB's Game
    hdu 5592 ZYB's Premutation (线段树+二分查找)
    智能指针原理代码
    友元类
    类与类指针的关系
    虚析构函数
  • 原文地址:https://www.cnblogs.com/WJJ-Dream/p/5829571.html
Copyright © 2011-2022 走看看