【问题标题】:C++ operator errorC++ 运算符错误
【发布时间】:2011-03-13 17:41:48
【问题描述】:

收到此错误:

C:\CodeBlocks\kool\praks3\vector.h|62|错误:将 'const Vector' 作为 'std::string Vector::toString() 的 'this' 参数传递 [with short unsigned int n = 2u]' 丢弃限定符|

使用此代码:

    #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;
}

【问题讨论】:

  • 恭喜。那么,你的问题是什么?我在上面没有看到一个问号。

标签: c++ templates operator-keyword


【解决方案1】:

制作toString方法const:

std::string toString() const;

template <unsigned short n>
std::string Vector<n>::toString() const{...}

这是因为您将const 限定符添加到operator&lt;&lt; 中的Vector。您只能在 const 限定对象上调用 const 限定方法。

【讨论】:

    【解决方案2】:

    这是因为您的向量被声明为 const,而您的 toString 运算符不是 const 方法。 因此,禁止使用 const 瞬间调用此方法。 如果在将向量转换为字符串时不编辑向量,则应将其声明为 const 方法:

    std::string toString() const;
    

    【讨论】:

      【解决方案3】:

      如果你有一个const Foo,你只能在它上面调用const 成员函数。所以声明为std::string toString() const

      【讨论】:

        猜你喜欢
        • 2012-02-29
        • 2015-07-04
        • 2012-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-31
        • 2015-11-19
        • 1970-01-01
        相关资源
        最近更新 更多