3、C++快速入门

参考书籍:

C++程序设计教程_第二版_钱能    //篇幅较少,适合快速学习

C++ Primer Plus  第六版  中文版   //篇幅较大,讲的非常详细

1、访问控制,类和对象

class是对struct的扩展,含有数据成员和成员函数

访问控制:private、public、protected,其中private声明的数据成员仅供类内部函数使用,public声明的类外部程序也可使用,默认的属性是private

int a:int是类型,a是变量

Person per :Person是类,per是对象

(在类中通过”this->数据成员”表示类内成员)

2、程序结构

  类定义(.h)/类实现(.cpp)

  如果在类中仅声明了函数,在类外怎么实现?void 类名::函数名(参数){函数体}

  A类实现Person类,其提供.h和.cpp,在A.h中仅声明类,其中类成员函数也仅声明,在A.cpp中通过类名::函数名来实现成员函数;B类实现main,B不关心Person类怎么实现,只需要#include <person.h>

  

  命名空间

  如果main文件中include多个h文件,同时这些h文件中存在同名的函数,其返回值和参数都一样,这个时候在h和其对于的cpp中把全部或者部分同名的函数使用namespace 名字A{}扩起来,在main中通过“名字A::同名函数名”还区分

eg:Person.h

 #include <stdio.h>

  namespace A{

  class Person{

  private:

    char *name;

    int age;

    char *work;

  public:

    void setName(char *name);

    int setAge(int age);

  }

  void printVersion(void);

  }

Person.cpp

  #include <stdio.h>

  #include "person.h"

  namespace A{

  void Person::setName(char *name)

  {

    this->name = name;

  }

  int Person::setAge(int age)

  {

    this->age = age;

    return 0;

  }

  void printVersion(void)

  {

    printf("Person111111");

  }

  }

Main.cpp

  #include <stdio.h>

  #incldue "person.h"

  int main(int argc,char **argv)

  {

    A::printVersion();

    return 0;

  }

猜你喜欢

转载自www.cnblogs.com/liusiluandzhangkun/p/9109278.html