c++ 类

类定义

class ClassName {
    private:
        //members that are not accessible from outside the class
    public:
        //members that are accessible from outside the class
}

示例代码

class Box {
    private :
        double length= 1.0;
        double width= 1.0;
        double heigth= 1.0;
    public :
        double volume() {
            return length*width*heigth;
        }
};

int main()
{
    Box mybox; /*与 C 中的结构体不同的是此处不需要加 class,直接就可以声明变量*/
    std::cout << mybox.volume() << std::endl;
#if 1 /*下边两种方式都是可行的,也就是说不是必须要声明一个对象*/
    std::cout << Box().volume() << std::endl;
    std::cout << Box{}.volume() << std::endl;
#endif
    return 0;
}

 

posted on 2018-07-16 15:56  rivsidn  阅读(65)  评论(0)    收藏  举报

导航