您的位置:首页 > 理论基础 > 数据结构算法

C++数据结构学习(一) 静态 非静态 成员及函数的访问

2013-03-05 20:06 239 查看
 

 

1,静态成员函数调用非静态成员函数

静态成员函数可以直接引用该类的 静态数据成员 和 静态成员函数,但不能直接引用 非静态数据成员 和 非静态成员函数,否则编译报错。如果要引用,必须通过参数传递的方式得到对象名,然后再通过对象名引用

#include<iostream>
using namespace std;
class Myclass
{
private:
int	m;	// 非静态数据成员
static	int	n;	// 静态数据成员
public:
Myclass();// 构造函数
static	int	getn(Myclass a);	// 静态成员函数
};
Myclass::Myclass()
{
m = 10;
}
int	Myclass::getn(Myclass a)
{
cout << a.m << endl;	// 通过类间接使用  非静态数据成员
return n;		// 直接使用  静态数据成员
}
int	Myclass::n = 100;	// 静态数据成员初始化
int	main()
{
Myclass app1;
cout << app1.getn(app1) << endl;	// 利用对象引用静态函数成员
cout << Myclass::getn(app1) << endl;	// 利用类名引用静态函数成员
}


非静态成员函数后面加const(加到非成员函数或静态成员后面会产生编译错误),表示成员函数隐含传入的this指针为const指针,决定了在该成员函数中,任意修改它所在的类的成员的操作都是不允许的(因为隐含了对this指针的const引用);唯一的例外是对于mutable修饰的成员。加了const的成员函数可以被非const对象和const对象调用,但不加const的成员函数只能被非const对象调用。

 

class A
{
private:
int m_a;
public:
A() : m_a(0) {}
int getA() const
{
return m_a; //同return this->m_a;。
}
int GetA()
{
return m_a;
}
int setA(int a) const
{
m_a = a; //这里产生编译错误,如果把前面的成员定义int m_a;改为mutable int m_a;就可以编译通过。

}
SetA(int a)
{
m_a = a; //同this->m_a = a;
}
};
A a1;
const A a2;
int t;
t = a1.getA();
t = a1.GetA();
t = a2.getA();
t = a2.GetA(); //a2是const对象,调用非const成员函数产生编译错误。
一般对于不需修改操作的成员函数尽量声明为const成员函数


 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: