【C++】成员运算符

一、A.B

A为对象或者结构体;

二、A->B

A为指针,->是成员提取,A->B是提取A中的成员B,A只能是指向类、结构、联合的指针。

class student
{
  public:      
  string name[20];
}

 

1、采用指针访问 student *xy,则访问时需要写成 *xy.name="hhhhh";等价于xy->name="hhhhh"。
2、采用普通成员访问 student xy,则访问时需要写成 xy.name="hhhhh"。

三、A::B

作用域运算符,A::B表示作用域A中的名称B,A可以是名字空间、类、结构。

1、类作用域,用来标明类的变量、函数

Human::setName(char* name);

2、命名空间作用域,用来注明所使用的类、函数属于哪一个命名空间的

std::cout << "Hello World" << std::endl;

3、全局作用域,用来区分局部、全局的

最容易被忽视的一种,很多时候写了一个全局函数或者想要调用一个全局函数,却发现IDE或者Editor找不到该函数,原因是因为局部函数与想要调用的全局函数名字一样,然后找了很久也找不到原因。

其实原因就是因为 【局部变量/函数】 与 【全局变量/函数】 的名字相同,IDE无法区分,这时候加上 :: 就可以调用到全局函数,访问到全局变量了。

例子:

把Linux下串口打开、关闭API

// fcntl.h文件下的全局函数open 
open (const char *__path, int __oflag, ...)

// unistd.h文件下的全局函数
extern int close (int __fd);

封装成一个串口库WzSerialPort.h、WzSerialPort.cpp:

// WzSerialPort.h
class WzSerialPort
{
public:
    // ...
    bool open();
    void close();
    // ...
};

以下的cpp文件,如果没有 :: 则会报错误,因为WzSerialPort库中有函数open和close,跟全局函数open和close名字相同,如果不做全局与局部的区分,则无法调用到全局函数:

// WzSerialPort.cpp
bool WzSerialPort::open()
{
    if( ::open(portname,O_RDWR|O_NOCTTY|O_NONBLOCK) != -1 )
        return true;
    else
        return false;
}
void WzSerialPort::close()
{
    ::close(fd);
}

出处

四、A:B

一般用来表示继承。

 

posted @ 2021-01-19 14:33  不溯流光  阅读(736)  评论(0编辑  收藏  举报