c++ 类的定义和使用

在 c++ 中 类的定义为 

class 类名

{

};切记,类的定义完成后要加上分号,这是很多初学者容易犯的错误。

类的成员及函数 分为 public private protect 三类,大家学过 面向对象自然知道三者的区分。

在类中,很重要的一点是 构造函数,该函数没有返回值,可以定义多个。在使用中要注意

ru

class student 
{
   public:
    stuent();
    student(string a,int b);           
}

在这里 仅仅定义了声明了 两个 构造函数,一个是带参数的,一个是不带参数的 ;

大家在使用中 

应该使用如下方法

student s1;               该方法调用的是没有参数的 构造函数     这里不能加括号 

但是 用这样方法就可以加括号  :student *s1 = new student(); 但是 这里定义的是一个指针对象,在使用的时候需要 s1->

student s1("sa",12); 该方法调用的是有参数的构造函数

参考函数

#include<iostream>
#include<string>
using namespace std;

class student
{
public:
    student();//构造函数
    student(int a,string b,string c);//带有参数的构造函数
    void say()
    {    cout <<"大家好,我叫" <<name<<"我今年"<<age<<"岁,我是"<<grade<<"级的学生"<<endl;
    }//自我介绍
    
private:
    int age;
    string name;
    string grade;

};

student::student()
{

    age = 20;
    name = "hyf1";
    grade = "2013";
    cout<<"这是没带参数的函数创造的"<<endl;
}

student::student(int a, string b,string c)
{
    age = a;
    name = b;
    grade = c;
    cout<<"这是带参数的函数创造的"<<endl;
}
/*
void student::say()
{
    cout <<"大家好,我叫" <<name<<"我今年"<<age<<"岁,我是"<<grade<<"级的学生"<<endl;
}
*/
int main()
{
    printf("asdasd");
    //student s1;
    student *s1 = new student();
    student s2(21,"hyf","2013");
    s1->say();
    s2.say();
    return 0;
}
原文地址:https://www.cnblogs.com/loveincode/p/4410052.html