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

C++的重要概念(综述)

时间:2016-04-13 18:49:05      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

1、变量和类型

  1.1、标识符(字母数字下划线)

     标识符不能使用关键字,C++区分大小写

alignas, alignof, and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, char16_t, char32_t, class, compl, const, constexpr, const_cast, continue, 
decltype, default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, noexcept, not, not_eq, nullptr, operator, or, or_eq, private, protected, public, register, reinterpret_cast, return, short, signed, sizeof, static,
static_assert, static_cast, struct, switch, template, this, thread_local, throw, true, try, typedef, typeid, typename, union, unsigned, using, virtual, void, volatile,
wchar_t, while, xor, xor_eq

  1.2、基本数据类型

     char,char16_t,char32_t,wchar_t,int ,short ,long ,long long,float,double,signed,unsigned,bool void,decltype(nullptr)

     8bit---256    16bit---65536       32bit --- 4billion     64bit----18billion billion

  1.3、变量初始化

      int x=0;

      int x(0);

      int x{0};

  1.4、类型推断 auto decltype

     

int    foo = 0;
auto    bar = foo;    //等效于 int    bar = foo;


int    foo = 0;
decltype(foo)    bar;        //等效于 int    bar;

  1.5 字符串类型

    string str = "This is a string.";

2. 常量

  字面值(数字的和字符的)

    1415 -123 0xFF  3.0   6.2e-19    ‘Z‘    "Gello"  "Who is it ?"

    75  75u  75L   大小不定  unsigned long

    ‘\n‘  new line ‘\t‘  tab

  字符串前缀

  u"Hello" 每个字符用char16_t存储    U"Hello" 每个字符用char32_t存储  L"Hello" 每个字符用wchar_t存储(根据具体编译器)

  u8"Hello" UTF-8存储

3.操作符

  赋值(=)算数五种 ( +, -, *, /, % )

  组合(+=, -=, *=, /=, %=, >>=, <<=, &=, ^=, |=)

  自增自减 (++, --)

  关系比较 ( ==, !=, >, <, >=, <= )

  逻辑三种 ( !, &&, || )

  三元条件( ? )

  逗号 ( , ) sizeof

  

 

LevelPrecedence groupOperatorDescriptionGrouping
1 Scope :: scope qualifier Left-to-right
2 Postfix (unary) ++ -- postfix increment / decrement Left-to-right
() functional forms
[] subscript
. -> member access
3 Prefix (unary) ++ -- prefix increment / decrement Right-to-left
~ ! bitwise NOT / logical NOT
+ - unary prefix
& * reference / dereference
new delete allocation / deallocation
sizeof parameter pack
(type) C-style type-casting
4 Pointer-to-member .* ->* access pointer Left-to-right
5 Arithmetic: scaling * / % multiply, divide, modulo Left-to-right
6 Arithmetic: addition + - addition, subtraction Left-to-right
7 Bitwise shift << >> shift left, shift right Left-to-right
8 Relational < > <= >= comparison operators Left-to-right
9 Equality == != equality / inequality Left-to-right
10 And & bitwise AND Left-to-right
11 Exclusive or ^ bitwise XOR Left-to-right
12 Inclusive or | bitwise OR Left-to-right
13 Conjunction && logical AND Left-to-right
14 Disjunction || logical OR Left-to-right
15 Assignment-level expressions = *= /= %= += -=
>>= <<= &= ^= |=
assignment / compound assignment Right-to-left
?: conditional operator
16 Sequencing , comma separator Left-to-right

 

4.stringstream

   string mystr("1203");

   int myint;

   stringstream(mystr) >> myint;    //myint = 1203

 

5、语句和流程控制

  选择: if and else 和 switch

  循环 (loops)

    while do-while for

  跳转 break continue goto

  C++11新增:基于范围的循环

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

int main ()
{
  string str {"Hello!"};
  for (char c : str)
  {
    std::cout << "[" << c << "]";
  }
  std::cout << \n;
}
//输出 [H][e][l][l][0][!]

6.函数

  函数的声明,内联函数,参数传递,

  参数的默认值

    

#include <iostream>
using namespace std;

int divide (int a, int b=2)
{
  int r;
  r=a/b;
  return (r);
}

int main ()
{
  cout << divide (12) << \n;        //6
  cout << divide (20,4) << \n;       //5
  return 0;
}

7. 重载和模板

  

// overloading functions
#include <iostream>
using namespace std;

int operate (int a, int b)
{
  return (a*b);
}

double operate (double a, double b)
{
  return (a/b);
}

int main ()
{
  int x=5,y=2;
  double n=5.0,m=2.0;
  cout << operate (x,y) << \n;
  cout << operate (n,m) << \n;
  return 0;
}

 上面这个函数体是不一样的,下面这种函数体一样的

// overloaded functions
#include <iostream>
using namespace std;

int sum (int a, int b)
{
  return a+b;
}

double sum (double a, double b)
{
  return a+b;
}

int main ()
{
  cout << sum (10,20) << \n;
  cout << sum (1.0,1.5) << \n;
  return 0;
}

对于一样的我们可以做模板

// function template
#include <iostream>
using namespace std;

template <class T>    //这个类型是相同
T sum (T a, T b)
{
  T result;
  result = a + b;
  return result;
}

int main () {
  int i=5, j=6, k;
  double f=2.0, g=0.5, h;
  k=sum<int>(i,j);
  h=sum<double>(f,g);
  cout << k << \n;
  cout << h << \n;
  return 0;
}
// function templates
#include <iostream>
using namespace std;

template <class T, class U>      //两个不同的类型
bool are_equal (T a, U b)
{
  return (a==b);
}

int main ()
{
  if (are_equal(10,10.0))
    cout << "x and y are equal\n";
  else
    cout << "x and y are not equal\n";
  return 0;
}
// template arguments
#include <iostream>
using namespace std;

template <class T, int N>   //模板有一个int型参数N
T fixed_multiply (T val)
{
  return val * N;
}

int main() {
  std::cout << fixed_multiply<int,2>(10) << \n;
  std::cout << fixed_multiply<int,3>(10) << \n;
}

8.namespace和using

  

// namespaces
#include <iostream>
using namespace std;

namespace foo
{
  int value() { return 5; }        //foo::value()
}

namespace bar
{
  const double pi = 3.1416;
  double value() { return 2*pi; }     //bar::value()
}

int main () {
  cout << foo::value() << \n;
  cout << bar::value() << \n;
  cout << bar::pi << \n;
  return 0;
}
// using
#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

int main () {
  using first::x;
  using second::y;
  cout << x << \n;
  cout << y << \n;
  cout << first::y << \n;
  cout << second::x << \n;
  return 0;
}
// using
#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
  int y = 10;
}

namespace second
{
  double x = 3.1416;
  double y = 2.7183;
}

int main () {
  using namespace first;
  cout << x << \n;
  cout << y << \n;
  cout << second::x << \n;
  cout << second::y << \n;
  return 0;
}
// using namespace example
#include <iostream>
using namespace std;

namespace first
{
  int x = 5;
}

namespace second
{
  double x = 3.1416;
}

int main () {
  {
    using namespace first;
    cout << x << \n;
  }
  {
    using namespace second;
    cout << x << \n;
  }
  return 0;
}

9.数组(两种)

#include <iostream>

using namespace std;

int main()
{
  int myarray[3] = {10,20,30};

  for (int i=0; i<3; ++i)
    ++myarray[i];

  for (int elem : myarray)
    cout << elem << \n;
}
#include <iostream>
#include <array>
using namespace std;

int main()
{
  array<int,3> myarray {10,20,30};

  for (int i=0; i<myarray.size(); ++i)
    ++myarray[i];

  for (int elem : myarray)
    cout << elem << \n;
}

  以0结尾的字符数组和字符串 

char   str[] = "ABC is string.";
char   str1[] = {A,B,C, ,i,s, ,s,t,r,i,n,g,. ,0}
string str2 = "ABC is stirng."

10. 指针

  指针变量为0x00000000--- 0xFFFFFFFF内存空间地址映射

  指针变量就是可以保存一般变量的地址,函数的地址,所有的函数变量都有一个内存位置,这些都可以用地址来找到 void   (*funcptr)(int)  指向一个参数为int 无返回值的函数

11.动态内存分配

  C++新增new delete

  pointer = new type
  pointer = new type [number_of_elements]

  delete pointer;

  delete[] pointer;

  C++扩展于C,也支持malloc,calloc,realloc 和free的内存管理

int * foo;
foo = new int [5];

int * foo;
foo = new (nothrow) int [5];
if (foo == nullptr) {
  // error assigning memory. Take measures. 自己处理异常
}


// rememb-o-matic
#include <iostream>
#include <new>
using namespace std;

int main ()
{
  int i,n;
  int * p;
  cout << "How many numbers would you like to type? ";
  cin >> i;
  p= new (nothrow) int[i];
  if (p == nullptr)    //空指针,0??
    cout << "Error: memory could not be allocated";
  else
  {
    for (n=0; n<i; n++)
    {
      cout << "Enter number: ";
      cin >> p[n];
    }
    cout << "You have entered: ";
    for (n=0; n<i; n++)
      cout << p[n] << ", ";
    delete[] p;
  }
  return 0;
}

12.结构体,联合

  

结构体
struct product {
  int weight;
  double price;
} ;
product apple;
product banana, melon;
调用
apple.weight
apple.price
banana.weight
banana.price
melon.weight
melon.price

结构体指针
struct movies_t {
  string title;
  int year;
};

movies_t amovie;
movies_t * pmovie;
调用
pmovie->title 等价于
(*pmovie).title

注意  *pmovie.title等价于*(pmovie.title)  在这里是错误的title 不是指针 
点。比*的优先级高

联合

union mytypes_t { char c; int i; float f; } mytypes;

调用
mytypes.c
mytypes.i
mytypes.f


13. typedef 和using    功能一样,新旧类型前后形式不一样

  typedef char C;

  typedef unsigned int WORD;

  typedef char * pChar;

  typedef char field [50];

  using C = char;

  using WORD = unsigned int;

  using pChar = char *;

  using field = char [50];

14.类是C++的一个重要的概念,衍生于结构

  class class_name { access_specifier_1: member1; access_specifier_2: member2; ... } object_names;  //class_name是类型object是实例对象

  

#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    Rectangle ();
    Rectangle (int,int);
    int area (void) {return (width*height);}
};

Rectangle::Rectangle () {
  width = 5;
  height = 5;
}

Rectangle::Rectangle (int a, int b) {
  width = a;
  height = b;
}

int main () {
  Rectangle rect (3,4);
  Rectangle rectb;
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
  return 0;
}

  

// member initialization
#include <iostream>
using namespace std;

class Circle {
    double radius;
  public:
    Circle(double r) : radius(r) { }
    double area() {return radius*radius*3.14159265;}
};

class Cylinder {
    Circle base;
    double height;
  public:
    Cylinder(double r, double h) : base (r), height(h) {}
    double volume() {return base.area() * height;}
};

int main () {
  Cylinder foo (10,20);

  cout << "foo‘s volume: " << foo.volume() << \n;
  return 0;
}

  

// pointer to classes example
#include <iostream>
using namespace std;

class Rectangle {
  int width, height;
public:
  Rectangle(int x, int y) : width(x), height(y) {}
  int area(void) { return width * height; }
};


int main() {
  Rectangle obj (3, 4);
  Rectangle * foo, * bar, * baz;
  foo = &obj;
  bar = new Rectangle (5, 6);
  baz = new Rectangle[2] { {2,5}, {3,6} };
  cout << "obj‘s area: " << obj.area() << \n;
  cout << "*foo‘s area: " << foo->area() << \n;
  cout << "*bar‘s area: " << bar->area() << \n;
  cout << "baz[0]‘s area:" << baz[0].area() << \n;
  cout << "baz[1]‘s area:" << baz[1].area() << \n;       
  delete bar;
  delete[] baz;
  return 0;
}    

Classes can be defined not only with keyword class, but also with keywords struct and union.

The keyword struct, generally used to declare plain data structures, can also be used to declare classes that have member functions, with the same syntax as with keyword class. The only difference between both is that members of classes declared with the keyword struct have public access by default, while members of classes declared with the keyword class have private access by default. For all other purposes both keywords are equivalent in this context.

Conversely, the concept of unions is different from that of classes declared with struct and class, since unions only store one data member at a time, but nevertheless they are also classes and can thus also hold member functions. The default access in union classes is public.

类型的定义class ,struct ,union 其实本质上是一样的,不过class默认的是private,结构和联合是全部可见的,而且联合某一时刻智能当做一种

 

C++的重要概念(综述)

标签:

原文地址:http://www.cnblogs.com/hinice/p/5387273.html

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