1、类的数据成员(类中声明的变量)和成员函数(类定义中声明的函数)属于该类的类域。非成员函数在全局命名域内定义。
2、在类域内,类的成员可以被该类的所有成员函数直接访问,并且可以按名字引用。
在类域外,通过对象的句柄,对象名、对象的引用、指向对象的指针类型之一引用public类型的类成员。对象、引用或指针的类型制定了可供客户访问的接口(成员函数)。
3、类的成员函数只能被该类的其他成员函数重载,重载成员函数只需要在类定义中提供重载成员函数各个版本的原型,并为该函数各个版本提供不同的函数定义。
//通过各种类型的对象句柄--对象名、对象的引用和指针对象的指针,访问对象的成员函数
#include<iostream>
using namespace std;
class Count{
public:
void setX(int value){
x = value;
}
void print(){
cout << x << endl;
}
private:
int x;
};
int main(){
Count counter;//创建类对象
Count *counterPtr = &counter;//为类对象创建指针
Count &counterRef = counter;//对象名引用
cout << "Set x to 1 and print using the object's name:";
counter.setX(1);
counter.print();
cout << "Set x to 2 and print using a reference to an object:";
counter.setX(2);
counter.print();
cout << "Set x to 3 and print using a pointer to an object:";
counterPtr->setX(3);
counterPtr->print();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)