C++程序设计方法2:基本语法

初始化列表

int a[] = {1,2,3};

int a[]{1,2,3}

以上两个式子等价

int a = 3+5;

int a = {3+5};

int a(3+5);

int a{3+5};

以上式子等价

int *i = new int(10);

double *d = new double{1.2f};

变量的类型推导与基于范围的循环

使用decltype可以对变量或者表达式结果的类型进行推导,如:

#include <iostream>

using namespace std;

struct
{
char *name;
}anon_u; struct
{
int d;
decltype(anon_u)id;
}anon_s[];//匿名的struct数组 int main()
{
decltype(anon_s)as;
cin >> as[].id.name;
}

基于范围的for循环语句

基于范围的for循环:在循环头的圆括号中,由冒号:分为两部分,第一部分用于迭代的变量,第二个部分用于表示将被迭代的范围如:

#include <iostream>
using namespace std; int main()
{
int arr[] = { ,, };
for (int e:arr)//for(auto e:arr)
{
cout << e << endl;
}
return ;
}

追踪返回类型的函数

可以将函数的返回类型的声明信息放到函数参数列表的后边进行声明,如:
普通函数的声明形式:

int func(char*ptr, int val);

zz追踪返回类型的函数的声明形式:
auto func(char *ptr, int val)->int;

追踪返回类型在原本函数返回值的位置使用auto关键字

成员函数的定义:类内部定义和类的外部定义

友元

有时候需要允许某些函数访问对象的私有成员,可以通过声明该函数为类的“友元”来实现

#include <iostream>
using namespace std; class Test
{
int id;
public:
friend void print(Test obj);
}; void print(Test obj)
{
cout << obj.id << endl;
}
//Test类中声明了Test类的友元函数print,该函数在实现时可以访问Test类定义的对象的私有成员;

在定义元素为对象的数组(ClassName array_var[NUM];)时,类必须提供默认构造函数的定义;

在构造函数的初始化列表中,还可以调用其他构造函数,被称为“委派构造函数”

class Info
{
public:
Info() { Init(); }
Info(int i) :Info() { id = i; }
Info(char c) :Info() { gender = c; }
private:
void Init(){}
int id{ };
char gender{ 'M' };
};

拷贝构造函数

函数调用时以类的对象为形参或者返回类的对象时,编译器会生成自动调用“拷贝构造函数”,在已有对象基础上生成新的对象;

拷贝构造函数是一种特殊的构造函数,他的参数是语言规定的,是同类对象的常量引用;

语义上:用参数对象的内容初始化当前对象

class Person

{

int id;

public:
person(const Person &src) {id = src.id;}

}

拷贝构造函数的例子:

#include <iostream>
using namespace std; class Test
{
public:
Test() { cout << "Test()" << endl; }
Test(const Test& src) { cout << "Test(const Test&)" << endl; }
~Test() { cout << "~Test()" << endl; }
}; void func1(Test obj)
{
cout << "func1()" << endl;
} Test func2()
{
cout << "func2()" << endl;
return Test();
} int main()
{
cout << "main()" << endl;
Test t;
func1(t);
t = func2();
return ;
}
上一篇:一个简单的通用Makefile实现


下一篇:史上最全的大厂Mysql面试题在这里!