struct A {
int *ptr;
};
int k = 5, r = 6;
const A a = {&k};
a.ptr = &r; // !error
*a.ptr = 7; // no error
class CTextBlock {
public:
...
std::size_t length() const;
private:
char *pText;
std::size_t textLength; // last calculated length of textblock
bool lengthIsValid; // whether length is currently valid
};
const int i; i = 5; // !error const int j = 10; // ok
const int COMPILE_CONST = 10; const int RunTimeConst = cin.get(); int a1[COMPLIE_CONST]; // ok in C++ and error in C int a2[RunTimeConst]; // !error in C++
//a.cpp extern const int M = 20; //b.cpp extern const int M;
const int *p1; // p1 is a non-const pointer and points to a const int int * const p2; // p2 is a const pointer and points to a non-const int const int * const p3; // p3 is a const pointer and points to a const it const int *pa1[10]; // pa1 is an array and contains 10 non-const pointer point to a const int int * const pa2[10]; // pa2 is an array and contains 10 const pointer point to a non-const int const int (* p4)[10]; // p4 is a non-const pointer and points to an array contains 10 const int const int (*pf)(); // pf is a non-const pointer and points to a function which has no arguments and returns a const int ...
int i; const int *cp = &i; int *p = const_cast<int *>(cp); const int *cp2 = static_cast<const int *>(p); // here the static_cast is optional
class B {
public:
B(): name("aaa") {
name = "bbb"; // !error
}
private:
const std::string name;
};
// a.h
class A {
...
static const std::string name;
};
// a.cpp
const std::string A::name("aaa");
// a.h
class A {
...
static const int SIZE = 50;
};
// a.cpp
const int A::SIZE = 50; // if use SIZE as a variable, not a macro
class A {
public:
int &operator[](int i) {
++cachedReadCount;
return data[i];
}
const int &operator[](int i) const {
++size; // !error
--size; // !error
++cachedReadCount; // ok
return data[i];
}
private:
int size;
mutable cachedReadCount;
std::vector<int> data;
};
A &a = ...;
const A &ca = ...;
int i = a[0]; // call operator[]
int j = ca[0]; // call const operator[]
a[0] = 2; // ok
ca[0] = 2; // !error
int &A::operator[](int i) {
return const_cast<int &>(static_cast<const A &>(*this).operator[](i));
}
constexpr int Inc(int i) {
return i + 1;
}
constexpr int a = Inc(1); // ok
constexpr int b = Inc(cin.get()); // !error
constexpr int c = a * 2 + 1; // ok
struct A {
constexpr A(int xx, int yy): x(xx), y(yy) {}
int x, y;
};
constexpr A a(1, 2);
enum {SIZE_X = a.x, SIZE_Y = a.y};
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有