C++操作员错误
收到此错误:
C:\CodeBlocks\kool\praks3\vector.h|62|错误:传递 'const Vector<2u>'作为 'std::string Vector::toString() [with Short unsigned int n = 2u]' 的 'this' 参数丢弃限定符|
用这个代码:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <sstream>
template <unsigned short n>
class Vector {
public:
std::vector<float> coords;
Vector();
Vector(std::vector<float> crds);
float distanceFrom(Vector<n> v);
std::string toString();
template <unsigned short m>
friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);
};
template <unsigned short n>
std::string Vector<n>::toString() {
std::ostringstream oss;
oss << "(";
for(int i = 0; i < n; i++) {
oss << coords[i];
if(i != n - 1) oss << ", ";
}
oss << ")";
return oss.str();
}
template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
out << v.toString(); // ERROR HEEEERE
return out;
}
getting this error:
C:\CodeBlocks\kool\praks3\vector.h|62|error: passing 'const Vector<2u>' as 'this' argument of 'std::string Vector::toString() [with short unsigned int n = 2u]' discards qualifiers|
with this code:
#include <iostream>
#include <vector>
#include <cmath>
#include <string>
#include <sstream>
template <unsigned short n>
class Vector {
public:
std::vector<float> coords;
Vector();
Vector(std::vector<float> crds);
float distanceFrom(Vector<n> v);
std::string toString();
template <unsigned short m>
friend std::ostream& operator <<(std::ostream& out, const Vector<m>& v);
};
template <unsigned short n>
std::string Vector<n>::toString() {
std::ostringstream oss;
oss << "(";
for(int i = 0; i < n; i++) {
oss << coords[i];
if(i != n - 1) oss << ", ";
}
oss << ")";
return oss.str();
}
template <unsigned short m>
std::ostream& operator<<(std::ostream& out, const Vector<m>& v) {
out << v.toString(); // ERROR HEEEERE
return out;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
toString
方法设为const
:这
是因为您将
const
限定符添加到中的
。您只能对Vector
运算符<<const
限定对象调用const
限定方法。Make the
toString
methodconst
:and
That's because you add the
const
qualifier to theVector
in theoperator<<
. You are only allowed to callconst
qualified methods onconst
qualified objects.这是因为您的向量被声明为 const,而您的 toString 运算符不是 const 方法。
因此,禁止使用 const 实例调用此方法。
如果在将向量转换为字符串时不对其进行编辑,则应将其声明为 const 方法:
This is because your vector is declared as const, while your toString operator is not a const method.
Therefore, calling this method is forbidden with a const instant.
If you do not edit the vector while converting it to string, you should declare it as a const method :
如果您有一个
const Foo
,则只能调用它的const
成员函数。因此将其声明为std::string toString() const
。If you have a
const Foo
, you can only invokeconst
member functions on it. So declare it asstd::string toString() const
.