码迷,mamicode.com
首页 > 编程语言 > 详细

C++ --> 类(Classes)

时间:2015-07-27 22:29:53      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:

1.类的定义:C++中使用关键字 class 来定义类, 其基本形式如下:

技术分享
1 class 类名
2     {
3         public:
4             //公共的行为或属性
5 
6         private:
7             //公共的行为或属性
8     };
View Code

说明:
①. 类名 需要遵循一般的命名规则;
②. public 与 private 为属性/方法限制的关键字, private 表示该部分内容是私密的, 不能被外部所访问或调用, 只能被本类内部访问; 而 public 表示公开的属性和方法, 外界可以直接访问或者调用。
   一般来说类的属性成员都应设置为private, public只留给那些被外界用来调用的函数接口, 但这并非是强制规定, 可以根据需要进行调整;
③. 结束部分的分号不能省略。

例:

 

技术分享
#include <iostream>

using namespace std; 

class Point
{
    public :
        void SetPoint(int x , int y)
        {
            xPost = x;
            yPost = y;
        }

        void PrintPoint()
        {
            cout <<"============================================"  << endl; 
            cout << " x = " << xPost << endl;
            cout << " y = " << yPost << endl;
        }
    private :
        int xPost;
        int yPost;
};

int main() 
{   

    cout <<"============================================"  << endl; 
    Point M;        //用定义好的类创建一个对象 点M
    M.SetPoint(10, 20); //设置 M点 的x,y值
    M.PrintPoint();     //输出 M点 的信息
    cout <<"============================================"  << endl;
    while(1)
    {
          
    }

    return 0;
}
View Code
技术分享
#include <iostream>

using namespace std; 

class Point
{
    public :
        void SetPoint(int x , int y);
        void PrintPoint();
    private :
        int xPost;
        int yPost;
};

void Point::SetPoint(int x , int y)
{
    xPost = x;
    yPost = y;
}

void Point::PrintPoint()
{
    cout <<"============================================"  << endl; 
    cout << " x = " << xPost << endl;
    cout << " y = " << yPost << endl;
}

int main() 
{   

    cout <<"============================================"  << endl; 
    Point M;        //用定义好的类创建一个对象 点M
    M.SetPoint(10, 20); //设置 M点 的x,y值
    M.PrintPoint();     //输出 M点 的信息
    cout <<"============================================"  << endl;
    while(1)
    {
          
    }

    return 0;
}
View Code

 

C++ --> 类(Classes)

标签:

原文地址:http://www.cnblogs.com/love29850706/p/4681356.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!