在程序设计中我们会经常调用函数,调用函数就会涉及参数的问题,那么在形参列表中const形参与非const形参对传递过来的实参有什么要求呢? 先来看一个简单的例子: #include <iostream> #include <string> using namespace std; void print_str(const string s) { cout<<s<<endl; } int main() { print_str("hello world…
void print1(int a) { cout<<a<<endl; } void print2(const int& a) { cout<<a<<endl; } void print3(int& a) { cout<<a<<endl; } int main() { ; int& b = a; const int& c = a; print1(a); print1(b); print1(c); pri…
举个例子, void f(const int &x) 和 void f(int &x) 是不同的函数. 函数的返回值不能作为区分…
一.类MyClass 二.主函数调用 三.结果…
转自:http://blog.csdn.net/u011068702/article/details/64443949 1.看代码 2.编译结果 3.分析和解决 就拿f(a + b)来说,a+b的值会存在一个临时变量中,当把这个临时变量传给f时,由于f的声明中,参数是int&,不是常量引用,因为c++编译器的一个关于语义的限制.如果一个参数是以非const引用传入,c++编译器就有理由认为程序员会在函数中修改这个值,并且这个被修改的引用在函数返回后要发挥作用.但如果你把一个临时变量当作非cons…
成员函数后面加const,表示在该函数中不能对类的数据成员进行改变,比如下面的代码: #include <stdio.h> class A { private: mutable int aa; public: A(){} int x() { printf("no const\n"); return aa++; } int x() const { printf("const\n"); return aa++; } }; int main() { A a1;…
int f (int & I) { cout<<I<<std::endl; } void main() { long L; f(L); // 编译不过 f((int)L); // 编译不过 f((int&)L);// 编译过 } 编译不会通过,这种情况下pL不会自动转换成int *,因为类型转换会生成临时变量,不能接收函数返回值 void func(int *& a){}; void * p; int * pint; func(pint); func((in…
[源码下载] 不可或缺 Windows Native (18) - C++: this 指针, 对象数组, 对象和指针, const 对象,  const 指针和指向 const 对象的指针, const 对象的引用 作者:webabcd 介绍不可或缺 Windows Native 之 C++ this 指针 对象数组 对象和指针 const 对象 const 指针和指向 const 对象的指针 const 对象的引用 示例1.CppEmployee 类CppEmployee.h #pragma…
从成员函数说起 在说const成员函数之前,先说一下普通成员函数,其实每个成员函数都有一个隐形的入参:T *const this. int getValue(T *const this) { return val; } const成员函数 声明形式是:int getValue() const; 编译器内部实现如下 int getValue(const T* const this) { return val; } 表示this指针指向的内容是不可改变的,所以当试图修改val时会编译报错. cons…
Static_cast可以对对象也可以对指针也可以对引用,但是const_cast只可以对指针和引用使用,后者不可以对对象用,如果你要把一个const值转化为非const值只能用隐式执行或通过使用static_cast.C 样式转换或函数样式转换执行. 比如: const int aa = 10; //int bb = const_cast<int>(aa);错误 int bb = int(aa);//传统的c转化方式 int bb = static_cast<int>(aa);/…