对象的常指针和常引用
-----------------siwuxie095
对象的常指针和对象的常引用
看如下实例:
定义一个坐标类:Coordinate
在实现时:
在使用时:
(1)如果使用对象指针和对象引用
(2)如果使用对象的常指针和对象的常引用
因为coor2 是常引用,只具有读权限,而 getX() 的隐藏参数 this,
却要求读写权限的参数,同理,pCoor 是常指针 …
下面是一种更复杂的情况:
这里的const 在 * 和 pCoor 之间,一旦指向了 coor1,就不能再
指向另外的对象了
pCoor 虽然用 const 修饰了,但它的修饰位置却在中间,意味着它
不能再指向其他对象,但它本身所指向的对象的内容却是可变的,即
pCoor 是一个具有读写权限的指针(只限于它指向的对象可以读写)
程序:
Coordinate.h:
class Coordinate { public: Coordinate(int x,int y); ~Coordinate(); void setX(int x); int getX(); void setY(int y); int getY(); void printInfo() const; private: int m_iX; int m_iY; }; |
Coordinate.cpp:
#include"Coordinate.h" #include <iostream> using namespace std;
Coordinate::Coordinate(int x, int y) { m_iX = x; m_iY = y; cout << "Coordinate()" << endl; }
Coordinate::~Coordinate() { cout << "~Coordinate()" << endl; }
void Coordinate::setX(int x) { m_iX = x; }
int Coordinate::getX() { return m_iX; }
void Coordinate::setY(int y) { m_iY = y; }
int Coordinate::getY() { return m_iY; }
void Coordinate::printInfo() const { cout << m_iX << "," << m_iY << endl; } |
main.cpp:
#include <stdlib.h> #include"Coordinate.h" using namespace std;
int main(void) { Coordinate coor1(3,5); Coordinate coor2(7, 9); //对象的常引用只能调用常成员函数 const Coordinate &coor3 = coor1; //对象的常指针还可以指向其他对象只能调用常成员函数 const Coordinate *pCoor1 = &coor1; //只能指向coor1 不能再指向其他但是可以调用所有的函数(常成员函数和普通成员函数) Coordinate *const pCoor2 = &coor1;
coor3.printInfo();
pCoor1->printInfo(); pCoor1 = &coor2; pCoor1->printInfo();
pCoor2->setX(11); pCoor2->printInfo();
system("pause"); return0; } |
【made by siwuxie095】