现在的位置: 首页 > 综合 > 正文

c++ const friend

2014年01月09日 ⁄ 综合 ⁄ 共 1944字 ⁄ 字号 评论关闭

class COperator
{
public:
int m_x;
COperator(){printf("COperator default constructors\n");}
//RefPtr& operator=(const PassRefPtr<T>&);
COperator(const COperator& src){m_x = src.m_x;printf("COperator copy constructors\n");};
COperator& operator=(const COperator& src){m_x = src.m_x; return *this;};
};

COperator& testfunc( COperator& a)
{
	a.m_x++;
	return a;
}

int main()
{
COperator a; 
COperator b;
//b=a;
b=testfunc(a);  
return 0;
}

no COperator copy constructors called.

copy constructor use reference;

1.const as "const variable"

2.function parameters
together with "&"
int add(int &a);//can be modified
int add(const int &a);//can't be modified 
//but more efficient than int add(int a); no value copy
3.override function
int add();
int add() const;

//different function;

//only member function can use const , c function can't.

4.return value

class A;
const A& add();
const int&  fun_return_const_c() {return k;}
int& const  fun_return_const_c() {return k;}//const will be omitted

the return value of add(), can't use as left value.

//only has significance when the return value is a refrence.

5.const member of class
must be initialized in the constructor function list.
only const function can visit const member.?
6.const member function
class{
int a;
void adda()const{a++;}//cant modify
}

const function cant modify member of the class.

//sometime we need to modify variable in the const function, so we need mutable variable.

mutable int m_iTimes;
void ClxTest::Output() const
{
 cout << "Output for test!" << endl;
 m_iTimes++;
}  

it's OK with mutable

7.const object
nothing in the object can be modified.

it can only call const function

友元
1.友元不是成员
2.定义在类内
3.在类内声明
4.友元定义在private和public都一样
友元函数
在该类内部声明的函数,可以被任何其他类使用来访问该类的私有变量。

inline
只是一个建议,编译器可以忽略

inline 在-E的时候不会被展开,只有编译的时候才会体现
查看一个内联函数是否被展开,没有非常优雅的方式
a.gcc -S
b.打印堆栈
all failed, I don't know

静态成员函数:

(1)普通数据成员属于类的一个具体的对象,只有对象被创建了,普通数据成员才会被分配内存。而静态数据成员属于整个类,即使没有任何对象创建,类的静态数据成员变量也存在。

  (2)因为类的静态数据成员的存在不依赖与于任何类对象的存在,类的静态数据成员应该在代码中被显示的初始化,一定要在类外进行,例如上例。

  (3)外部访问类的静态成员只能通过类名来访问,例如:test::getCount()。

  (4)类的静态成员函数无法直接访问普通数据成员(可以通过类的指针等作为参数间接访问),而类的任何成员函数都可以访问类的静态数据成员。

  (5)静态成员和类的普通成员一样,也具有public、protected、private3种访问级别,也可以具有返回值、const修饰符等参数。

抱歉!评论已关闭.