gpt4 book ai didi

c++ - 模板类上的二元运算符重载

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:20:27 26 4
gpt4 key购买 nike

我最近试图衡量我的运算符重载/模板能力,并作为一个小测试,创建了下面的 Container 类。虽然此代码在 MSVC 2008(显示 11)下编译得很好并且可以正常工作,但 MinGW/GCC 和 Comeau 都在 operator+ 过载时出现问题。因为我比 MSVC 更信任他们,所以我想弄清楚我做错了什么。

代码如下:

#include <iostream>

using namespace std;

template <typename T>
class Container
{
friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs);
public: void setobj(T ob);
T getobj();
private: T obj;
};

template <typename T>
void Container<T>::setobj(T ob)
{
obj = ob;
}

template <typename T>
T Container<T>::getobj()
{
return obj;
}

template <typename T>
Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs)
{
Container<T> temp;
temp.obj = lhs.obj + rhs.obj;
return temp;
}

int main()
{
Container<int> a, b;

a.setobj(5);
b.setobj(6);

Container<int> c = a + b;

cout << c.getobj() << endl;

return 0;
}

这是 Comeau 给出的错误:

Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
Copyright 1988-2008 Comeau Computing. All rights reserved.
MODE:strict errors C++ C++0x_extensions

"ComeauTest.c", line 27: error: an explicit template argument list is not allowed
on this declaration
Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs)
^

1 error detected in the compilation of "ComeauTest.c".

我很难让 Comeau/MingGW 参与进来,所以这就是我求助于你们的地方。我的大脑已经很久没有在 C++ 语法的重压下融化这么多了,所以我感到有点尴尬 ;)。

编辑:消除了初始 Comeau 转储中列出的(不相关的)左值错误。

最佳答案

感谢 to this forum posting,我找到了解决方案.本质上,您需要先有一个函数原型(prototype),然后才能在类中对它使用“friend”,但是您还需要声明该类才能正确定义函数原型(prototype)。因此,解决方案是在顶部有两个原型(prototype)定义(函数和类的)。以下代码在所有三个编译器下编译:

#include <iostream>

using namespace std;

//added lines below
template<typename T> class Container;
template<typename T> Container<T> operator+ (Container<T>& lhs, Container<T>& rhs);

template <typename T>
class Container
{
friend Container<T> operator+ <> (Container<T>& lhs, Container<T>& rhs);
public: void setobj(T ob);
T getobj();
private: T obj;
};

template <typename T>
void Container<T>::setobj(T ob)
{
obj = ob;
}

template <typename T>
T Container<T>::getobj()
{
return obj;
}

template <typename T>
Container<T> operator+ (Container<T>& lhs, Container<T>& rhs)
{
Container<T> temp;
temp.obj = lhs.obj + rhs.obj;
return temp;
}

int main()
{
Container<int> a, b;

a.setobj(5);
b.setobj(6);

Container<int> c = a + b;

cout << c.getobj() << endl;

return 0;
}

关于c++ - 模板类上的二元运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/962599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com