【发布时间】:2020-05-31 05:55:54
【问题描述】:
在 C++ 中,是否可以从类成员函数返回类的元素?
namespace translation2d
{
class translation2d
{
public:
double x;
double y;
public:
translation2d()
{
x=0;
y=0;
}
public:
translation2d translateBy(translation2d other);
//being interpreted as a constructor?
}
translation2d translation2d::translateBy(translation2d other)
{//I need this member function to return an object of type translation2d
x+=other.x;
y+=other.y;
}
};
【问题讨论】:
-
你试过了吗:return translation2d(); ?
-
通过调用
translateBy(...)修改您的translation2d对象。您需要返回当前translation2d对象的副本还是新的translation2d对象? -
“是”,类成员可以创建与定义它的类具有相同类型的对象。(不确定问题中还有什么问题..因此投票焦点- 必需。)