点(.)运算符在C ++编程语言中被称为“类成员访问运算符”,它用于访问类的公共成员。公共成员包含类的数据成员(变量)和成员函数(类方法)。
语法:
object_name.member_name;
考虑给定的类声明
class sample
{
private:
int a;
public:
int b;
void init(int a)
{this->a = a;}
void display()
{cout<<"a: "<<a<<endl;}
};在此类声明中,以下是可以通过“类成员访问运算符”访问的类成员:
公开数据成员: b
公共成员函数: init(),display()
这是完整的程序
#include <iostream>
using namespace std;
class sample
{
private:
int a;
public:
int b;
void init(int a)
{this->a = a;}
void display()
{cout<<"a: "<<a<<endl;}
};
int main(){
//对象声明
sample sam;
//赋值给a和back-
sam.init(100);
sam.b=200;
//打印值
sam.display();
cout<<"b: "<<sam.b<<endl;
return 0;
}输出结果
a: 100 b: 200
看以下main()函数中的语句
sam.init(100); -此语句将通过此公共成员函数将100分配给私有数据成员a。
sam.b = 200; -此语句将200分配给公共数据成员b。