【发布时间】:2018-01-26 06:35:28
【问题描述】:
我正在尝试创建与构造函数相同的操作符。
我为这个类创建了重载输出运算符<<,这很容易。
我只想输入nameOfObject+(value) 来创建foo 类的新实例。
我试过这个:
foo& operator+(int x, foo& f) {
f tmp = new foo(x);
return tmp;
}
但我收到错误消息说我需要在tmp 之后使用;;
#include <iostream>
#include <memory>
class foo {
private:
int x;
public:
foo(int x) { this->x = x; }
int getX() { return this->x; }
};
std::ostream& operator<< (std::ostream& text, foo& f) {
text << f.getX();
return text;
}
int main()
{
foo bar(2);
std::cout <<bar; //returns 2
return 0;
}
UPDATE_1:
例如,我的班级中有 heightOfTheTree 变量。使用foo tree1(5) - 普通构造函数我只想将 5 分配给我的变量。但是使用foo tree2+5,我想创建一个值乘以两倍的新对象(例如)。
【问题讨论】:
-
使用
f tmp = new foo(x);向我表明您并不精通该语言的基础知识。阅读a good book对你有好处。 -
类型叫什么,参数叫什么?
-
这个类似的问题可能会引起人们的兴趣:how to add three objects of same class in c++?(顺便说一句,标记为重复),我在其中为
operator+重载提出了多种解决方案。 -
您的问题表明您希望表达式
bar + n返回bar的副本,但您真的不希望它返回值为bar.getX() + n的bar 的副本吗?