c++ /Eclipse cdt,避免用不同的签名实现相同的函数
C++/Eclipse cdt, avoid to implement the same function but with different signature
我不知道我要问的问题是否取决于我正在使用的工具还是语言本身,但无论如何。
我有一个情况,我有"一个方法"声明了几次不同的签名。如:
class my_class {
public:
int getData();
int getData() const;
my_class operator+(my_class&,my_class&);
my_class operator+(const my_class&, const my_class&) const;
//other operators, other functions etc with similar feature
private:
int data;
};
你可以想象实现总是相同的,这只是签名的问题。是否有一种方法可以避免为这些函数编写两次相同的实现?
开始时,我认为应该执行从类型到const类型的强制转换,但显然我错了。
谢谢
-
你的重载没有正确声明。类成员二元运算符只能接受一个参数,另一个是隐式的
this
。 -
你不需要两个重载。操作符不应该改变操作数,因此仅使用const版本就足够了。
那么剩下的就是:
class my_class {
public:
int getData();
int getData() const;
my_class operator+(const my_class&) const;
//other operators, other functions etc with similar feature
private:
int data;
};
或非成员版本:
class my_class {
public:
int getData();
int getData() const;
friend my_class operator+(const my_class&, const my_class&);
//other operators, other functions etc with similar feature
private:
int data;
};
my_class operator+(const my_class&, const my_class&) {
// code
}
对于getData()
。它返回数据的副本,我假设它不会修改实例。那么const
过载也足够了
相关文章:
- 在命名空间内部还是外部实现 c++ 函数?
- 如何在C++中实现函数(f)(x)(y, z)(g)(r)
- 如何在C++中实现函数上的二叉搜索?
- 键按下事件错误 Qt 实现函数时
- 在子类之外实现函数导致未知错误
- 通过模板滥用实现函数式C++
- C++,实现函数"int next(std::string param)"时出现奇怪的编译器错误
- 我正在尝试创建自己的 strcat() 函数,而不是使用库实现函数<cstring>
- 如果未实现函数,则在链接时启用错误
- 用函数参数实现c++函数指针
- 如何在Android SDK中调用和实现C++函数
- 在 C++ RCPP 中实现 R 函数
- 实现函数模板填充多维对象
- 类的层次结构,试图在基本级别实现函数
- 用c++实现函数对象的自动检测类型
- 用shared_ptrs实现函数模板的C++实例化
- 在类中实现函数导致错误:成员引用基类型'ifstream (string)'不是结构或联合
- 用c++实现S函数.生成错误
- 引用可以用于实现函数重写吗
- 如何在c++中实现函数超时