mus*_*osu 7 c++ method-chaining
我必须实现一个Vector类,它设置一个多维向量的坐标,并在使用这个特定的代码调用时工作(我不能改变这部分):
const int NumOfDimensions = 5;
Vector x (NumOfDimensions);
x.Set(0, 1.1).Set(1, 1.2).Set(2, 1.3).Set(3, 1.4).Set(4, 1.5);
x.print();
Run Code Online (Sandbox Code Playgroud)
输出必须是这样的:
(1.1,1.2,1.3,1.4,1.5)
这是我尝试但无法让它工作:
class Vector {
float *coordinates;
int dimensions;
public:
Vector(int k)
{
coordinates = new float[k];
dimensions = k;
}
void Set(int k, float wsp)
{
//Vector x(k+1);
coordinates[k] = wsp;
//return x;
}
void print()
{
int i;
cout<<"(";
for(i=0; i<dimensions; i++)
cout<<coordinates[i]<<", ";
cout<<")"<<endl;
}
};
Run Code Online (Sandbox Code Playgroud)
所以我知道函数Set需要改变并且可能返回一个对象,但我尝试了很多不同的方法而且它不起作用.我应该如何修改它?
tad*_*man 12
如果您希望能够链接那种方法,则需要返回一个引用:
Vector& Set(int k, float wsp) {
// ...
return *this;
}
Run Code Online (Sandbox Code Playgroud)
我认为即使你在Python,Ruby等其他语言中看到很多这样的东西,那个界面也不是很C++.
你最好用它std::vector来存储你的coordinates,C风格的数组只是麻烦.此代码实际上有严重的内存泄漏,因为您没有取消分配delete[],没有定义析构函数.使用标准库容器可以减轻该责任.
你可以做的更多原生C++的另一件事是为它定义一个格式化程序,这样你就可以简单地将它转储到cout直接而不是让你有一个笨重的方法调用print它:
std::ostream& operator<<(std::ostream& stream, const Vector& vec);
Run Code Online (Sandbox Code Playgroud)
这将允许在任何流上使用该格式化器,而不仅仅是cout.