C++类内缺省函数

1.问题来源

我需要在C++的一个类内函数进行缺省参数处理,声明和定义分别分布在.h文件和.cpp文件中,这里如何进行缺省处理就是一个问题,而网络上很多对这种情况说明的不太好,于是就有了这篇文章。

2.正确做法

在.h文件声明函数时,直接写上缺省值,在.cpp文件中不写缺省值。
例如:
Cal.h中:

int add(int a, int b = 0);

Cal.cpp中:

int add(int a, int b) {
    return a + b;
}

3.其他方式报错

(1)报错:error: taking address of temporary [-fpermissive]

原因:.h文件中不写缺省,在.cpp文件中写缺省值。

(2)报错:error: default argument given for parameter 2 of ‘epoll_event Epoller::creatEpollEvent(int, uint32_t)’ [-fpermissive]

原因:.h和.cpp文件中全写缺省值。

posted @ 2022-06-08 15:10  云梦士  阅读(112)  评论(0编辑  收藏  举报