c++类使用

一、C++定义类(注意:结束部分的分号不能省略

class 类名
    {
        public:
            //公共的行为或属性

        private:
            //公共的行为或属性
    };

注意:类的成员变量在定义时不能进行初始化, 如 int xPos = 0; //错;

二、在类外定义成员函数

举例说明:

#include <iostream>

        using namespace std;

        class Point
        {
            public:
                void setPoint(int x, int y); //在类内对成员函数进行声明
                void printPoint();

            private:
                int xPos;
                int yPos;
        };

        void Point::setPoint(int x, int y) //通过作用域操作符 '::' 实现setPoint函数
        {
            xPos = x;
            yPos = y;
        }

        void Point::printPoint()       //实现printPoint函数
        {
            cout<< "x = " << xPos << endl;
            cout<< "y = " << yPos << endl;
        }

        int main()
        {
            Point M;        //用定义好的类创建一个对象 点M
            M.setPoint(10, 20); //设置 M点 的x,y值
            M.printPoint();     //输出 M点 的信息

            return 0;
        }

三、C++构造函数

举例说明:

 

#include <iostream>
using namespace std;

class Student{
private:
    char *name;
    int age;
    float score;

public:
    //声明构造函数
    Student();
    Student(char *, int, float);
    //声明普通成员函数
    void setname(char *);
    void setage(int);
    void setscore(float);
    void say();
};

//定义构造函数
Student::Student(){}
Student::Student(char *name1, int age1, float score1){
    name = name1;
    age = age1;
    score = score1;
}
//定义普通成员函数
void Student::setname(char *name1){
    name = name1;
}
void Student::setage(int age1){
    age = age1;
}
void Student::setscore(float score1){
    score = score1;
}
void Student::say(){
    cout<<name<<"的年龄是 "<<age<<",成绩是 "<<score<<endl;
}

int main(){
    //创建对象时初始化成员变量
    Student stu1("小明", 15, 90.5f);
    stu1.say();
   
    //调用成员函数来初始化成员变量的值
    Student stu2;
    stu2.setname("李磊");
    stu2.setage(16);
    stu2.setscore(95);
    stu2.say();

    return 0;
} 

 

 

class Counter
{

public:
         // 类Counter的构造函数
         // 特点:以类名作为函数名,无返回类型
         Counter()
         {
                m_value = 0;
         }
         
private:
      
         // 数据成员
         int m_value;
}

 

四、对象的作用域、可见域与生存周期
    类对象的作用域、可见域以及生存周期与普通变量的保持相同, 当对象生存周期结束时对象被自动撤销, 所占用的内存被回收, 需要注意的是, 如果对象的成员函数中有使用 new 或者 malloc 申请的动态内存程序不会对其进行释放, 需要我们手动进行清理, 否则会造成内存泄露。

posted @ 2015-10-21 15:17  likai_liche  阅读(312)  评论(0编辑  收藏  举报