目录
一,可变长数组
C99开始支持可变长数组:
void testf()
{
int n;
scanf("%d",&n);
int arr[n];
arr[3]=45;
printf("%d",arr[3]);
}
C++不支持,这是唯一C++没有的C语言的语法。
可变长数组只能是局部变量,不能是全局变量。
然而,一些编译器让C++也支持可变长数组,我推测应该是直接按照C语言中的逻辑进行编译。
二,伸缩型数组
C和C++都支持
typedef struct
{
int a;
char data[];
}st;
或者
typedef struct
{
int a;
char data[0];
}st;
第一种写法是C语言标准语法,第二种叫struct hack,不属于标准语法。
数组data是不占内存的,实际能分配多少内存,取决于给这个结构体分配多少内存,data说白了就是指向结构体的尾巴后面一个字节的指针。
相关文章:结构体大小和对齐值_nameofcsdn的博客-优快云博客
三,常量
1,字面值和只读变量、数组长度
在C++中,常量包括字面值和只读变量:
int a=12345;
const int b=123;
这里,12345是字面值,a是变量,b是只读变量。
12345是常量,b是常量,a不是常量。
在C中,常量只包括字面值,只读变量不是常量。
上述代码在C语言的解读是,12345是常量,b不是常量。
C和C++中,定义数组的大小都只能用常量。
所以C++有2种定义数组的方法:
const int b=123;
int c[123];
int d[b];
这2种写法都是正确的。
但是在C语言中,上述d数组如果是全局变量就是非法的,如果是局部变量那就是可变长数组。
2,const、运行期常量、编译期常量
关键字const叫做限定符,因为它限定了声明的含义。

const变量是区分编译期常量和运行期常量的
const int b=123;
int d[b];
这是的b编译期常量
int f(int a)
{
const int b=a;
int d[b];
cout<<sizeof(d)/sizeof(int);
return 0;
}
这里的b是运行期常量,它的值在编译期是未知的,数组d是可变长数组。
于是我在网上找到了另外一种代码,用array检测一个变量是不是常量:
#include<iostream>
#include <array>
using namespace std;
int main()
{
int a = 10;
const int b = a;
const int c = 10;
//array<int,b>arr;
array<int, c>arr2;
return 0;
}
用运行期常量给array对象分配空间是不行的,必须用编译期常量才行。
总之,const变量是区分编译期常量和运行期常量的,,而字面值当然都是编译期常量。
3,constexpr、常量表达式、CTFE
在上面的例子中,同样是const常量,有的是编译期常量,有的是运行期常量。
于是C++新增了constexpr关键字,对于编译期常量可以直接用constexpr来修饰。
#include<iostream>
#include <array>
using namespace std;
int main()
{
int a = 10;
const int b = a;
constexpr int c = 10;
//array<int,b>arr;
array<int, c>arr2;
return 0;
}
constexpr还可以用于CTFE,即Compile Time Function Execution
先看如下代码:
#include<iostream>
#include <array>
using namespace std;
const int f(int a)
{
return a*a;
}
int main()
{
// array<int,f(5)>arr;
return 0;
}
编译不过是因为,f(5)是运行期常量,而array需要的是编译期常量
把const换成constexpr之后:
#include<iostream>
#include <array>
using namespace std;
constexpr int f(int a)
{
return a*a;
}
int main()
{
array<int,f(5)>arr; //5是字面值
int a=5;
//array<int,f(a)>arr2; //a是变量
const int b=5;
array<int,f(b)>arr3; //b是编译期常量
const int c=a;
//array<int,f(c)>arr4; //c是运行期常量
return 0;
}
这样,5和b是编译期常量,所以f(5)和f(b)是编译期常量,而f(a)和f(c)都不是编译期常量,所以不能用来分配array对象。
总之,constexpr的作用是,在编译期运行函数,在输入编译期常量的条件下,可以返回编译期常量。
四,结构体
1,成员
(1)C++允许有内部成员函数,且允许该函数是虚函数,C的结构体内不允许有函数存在,但是可以有函数指针。所以C的结构体是没有构造函数、析构函数、和this指针的。
(2)C的结构体对内部成员变量的访问权限只能是public,而C++允许public,protected,private三种。
2,继承
C语言的结构体是不可以继承的,C++的结构体是可以从其他的结构体或者类继承过来的。
3,定义方式
(1)C语言定义结构体
(1)不带typedef
一种创建实例的写法:
struct A{
int x;
};
struct A a;
(2)先定义结构体,再typedef
同名定义,两种创建实例的写法:
struct A{
int x;
};
typedef struct A A;
struct A a;
A a2;
不同名定义,两种创建实例的写法:
struct A{
int x;
};
typedef struct A B;
struct A a;
B a2;
(3)typedef 加 结构体定义
同名定义,两种创建实例的写法:
typedef struct A{
int x

本文深入探讨了C/C++语言的重要特性,包括可变长数组、伸缩型数组、常量、结构体、auto类型推导、类型转换、内联函数等,并详细解析了字符串操作的具体方法。
最低0.47元/天 解锁文章
867

被折叠的 条评论
为什么被折叠?



