C++类的const成员函数 double Sales_item::avg_price() const { } const关键字表明这是一个const成员函数,它不可以修改Sales_item类的成员变量. 如果没有为一个类显示的定义任何的构造函数,编译器会自动为这个类生成默认的构造函数,成为“合成的默认构造函数”.这样的话,构造函数不会自动初始化内置类型的成员.对于类类型的成员,比如string,会用string自身的默认构造函数进行初始化. 复制形参函数调用的时候并不考虑形参是否非const…
类的const成员包括const数据成员和const成员函数: 1.const数据成员: 和普通的const变量一样,定义时初始化,且不能修改 2.const成员函数: const成员函数只能访问其他的const成员函数,而不能访问非const成员函数 const可以修饰static数据成员,在定义时初始化,但仍要在类外进行声明 const成员函数不能修改类的对象,即不能修改数据成员,但当数据成员被mutable修饰时,可以修改 const不能修饰static成员函数,因为const表示不修改类…
/*ca71a_c++_指向函数的指针_通过指针调用函数用typedef简化函数指针的定义简化前: bool(*pf)(const string&, const string &); bool(*pf2)(const string&, const string &); bool(*pf3)(const string&, const string &); 简化后: typedef bool(*cmpFcn)(const string &, const…
转自:http://www.cnblogs.com/Saints/p/6012188.html 构造器函数(Constructor functions)的定义和任何其它函数一样,我们可以使用函数声明.函数表达式或者函数构造器(见以前的随笔)等方式来构造函数对象.函数构造器和其它函数的区别在与它们的调用方式不同. 要以构造函数的方式调用函数,只需要在调用时在函数名称前加new 关键字,比如:function whatsMyContext(){ return this; }; 调用:new what…
我们知道类里面的const的成员函数一般是不允许改变类对象的,但是我们知道const 类型的指针是可以强制类型转出成非const指针的,同样的道理,this指针也可以被强制类型转换 class Y{ int i; public: Y(); void f()const; }; Y::Y(){ i=; } void Y::f()const{ //i++; 此时是错误的,因为此时this的指针类型是const Y* const this ((Y*) this)->i++; (const_cast<Y…
class A { public: A(){}; const int num; CString& s; } A::A() { cout<<A con<<endl; } void main() { A a; } 这是不过的,因为const成员变量需要在构造函数调用进入函数体之前就要被初始化,所以 C++有一种语法叫做 成员初始化列表. 构造函数改为 A::A():num(5):s(myString) { cout<<A con<<endl; } 这样c…
当类中用到一些固定值时,希望将其定义为const成员变量,防止被修改. 但因为const成员变量因为初始化之后就不能修改,因此只能在构造函数的初始化列表中初始化 如果是数组,则没有办法在初始化列表中初始化,必须定义为static,放在类外定义 例子: //const_array.h #include <iostream> using namespace std; class Base{ public: Base() : _cia(){cout << "Base const…
在我的文件里有这class NFDuration, NFDuration.h里是这样的: // A Duration represents the elapsed time between two instants // as an int64 nanosecond count. The representation limits the // largest representable duration to approximately 290 years. class NFDuration…
const成员变量 举个例子 #include <iostream> using namespace std; class A { public: A(int size) : SIZE(size) {}; private: const int SIZE; }; int main() { A a(); } 说明 在类中声明变量为const类型,但是不可以初始化 const常量的初始化必须在构造函数初始化列表中初始化,而不可以在构造函数函数体内初始化 但是 此时的const变量属于具体的一个对象,…
举个例子: 定义了一个类的const实例,怎么让他也能调用非能调用非const成员函数class foo{public:void test1() {cout << "I am not a const member function" << endl;}void test2()const {foo *temp = (foo*)this;//注意这个转换!!!temp->test1();}}; int main() {foo f;f.test2();retur…