【发布时间】:2016-11-07 11:54:14
【问题描述】:
下面的代码工作正常,按预期打印出 50。然而,我不明白的是,为什么不能编写相同的程序,只需对这段代码稍作改动。建议的两行代码被标记为错误代码 1 和 2。当它们替换它们左侧的当前工作代码时(即在 addStuff 和 main 中),我收到以下错误:
error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream}' and 'MyClass')|
我期望它的工作方式是:当addStuff(x,y) 在main() 的(坏)cout 行中被调用时,它首先评估x+y,其行为由operator+ 定义MyClass 重载成员函数。这应该只返回一个 MyClass 对象,然后调用 getVar 就没有问题了。
我在这里错过了什么?
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass(){}
MyClass(int a) : priV(a){}
MyClass operator+(MyClass otherMC)
{
MyClass newMC;
newMC.priV = this->priV + otherMC.priV;
return newMC;
}
int getVar(){return priV;}
void setVar(int v){priV=v;}
private:
int priV;
};
template <class gen>
gen addStuff(gen x, gen y)
{
return x+y; //Bad code 1: return (x+y).getVar();
}
int main()
{
MyClass x(20), y(30);
cout << addStuff(x,y).getVar() << endl; //Bad code 2: cout << addStuff(x,y) << endl;
}
【问题讨论】:
-
错误代码 1:返回错误类型。错误代码 2:为您想要处理的任何类型实现 ostream
标签: c++ function templates overloading operator-keyword