QT代码,重载函数d_func()声明形式分析和调用关系分析
#define X_DECLARE_PRIVATE(Class) \
inline Class##Private* d_func() { return reinterpret_cast<Class##Private *>(xGetPtrHelper(d_ptr)); } \
inline const Class##Private* d_func() const { return reinterpret_cast<const Class##Private *>(xGetPtrHelper(d_ptr)); } \
friend class Class##Private;
#include <stdio.h>
class A
{
public:
A(int a)
{
giCnt = a;
}
inline int* d_func()
{
printf("111\n");
return reinterpret_cast<int *>(&giCnt);
}
inline const int* d_func()
{
printf("222\n");
return reinterpret_cast<const int *>(&giCnt);
}
public:
int giCnt;
};
int main()
{
A a(4);
int* d = a.d_func();
return 0;
}
1、编译失败,函数返回值有区别,不构成重载,编译器认为是通一个函数,函数重定义,编译失败
#include <stdio.h>
class A
{
public:
A(int a)
{
giCnt = a;
}
inline int* d_func()
{
printf("111\n");
return reinterpret_cast<int *>(&giCnt);
}
inline int* d_func() const
{
printf("222\n");
return reinterpret_cast<int *>(&giCnt);
}
public:
int giCnt;
};
int main()
{
A a(4);
int* d = a.d_func();
return 0;
}
2、编译失败,失败信息如下:
error: reinterpret_cast from type ‘const int*’ to type ‘int*’ casts away qualifiers
return reinterpret_cast< int *>(&giCnt);
当成员函数加上const后,该函数会将所有的成员变量前增加const属性处理,因此&giCnt为const int*的类型
#include <stdio.h>
class A
{
public:
A(int a)
{
giCnt = a;
}
inline int* d_func()
{
printf("111\n");
return reinterpret_cast<int *>(&giCnt);
}
inline const int* d_func() const
{
printf("222\n");
return reinterpret_cast<const int *>(&giCnt);
}
public:
int giCnt;
};
int main()
{
A a(4);
a.d_func();
const A b(3);
b.d_func();
return 0;
}
3、编译成功,输出结果:
111
222