【问题标题】:Error C2676 binary '<<': 'std::ostream' does not define this operator or a conversion to a type acceptable to the predefined operator错误 C2676 二进制“<<”:“std::ostream”未定义此运算符或转换为预定义运算符可接受的类型
【发布时间】:2018-11-22 11:13:02
【问题描述】:

不明白编译错误C2676

下面的代码

#ifndef __VEC_3D_H__
#define __VEC_3D_H__

#include <vector>
#include <cmath>

namespace Internal
{
    /** very simple 3D vector/ point */
    class Vec3D
    {
    public:
        float mX;
        float mY;
        float mZ;

        /// null constructor
        Vec3D(void) {}

        /// construct from data
        Vec3D(float x, float y, float z) : mX(x), mY(y), mZ(z) {}

        inline friend std::ostream& operator<< (std::ostream& os, const Vec3D& v) 
        {
            os << "(" << v.mX << ", " << v.mY << ", " << v.mZ << ")";
            return os;
        }
    };

}

#endif

我在另一个类中放置了一个功能相同的代码,它编译并运行良好。这里有什么问题?

EDIT1:将 BOBVec3d 更正为 Vec3D,是一个错字

EDIT2:删除了using namespace Internal;,将它放在头文件中确实是败笔

【问题讨论】:

  • 在切线注释中,所有连续包含两个下划线的标识符以及所有以下划线和大写字母开头的标识符都被保留。在你自己的代码中定义这样的标识符是 UB。
  • using namespace Internal; 放在标题中有点违背了拥有命名空间的目的。

标签: c++ operator-overloading


【解决方案1】:

顶部缺少#include &lt;iostream&gt;

修复它。 (哦,C++ 中的编译错误可能是多么糟糕……)

【讨论】:

  • 您可能想查看诸如Resharper for C++Visual Assist X 之类的扩展程序,它们会犯这种几乎不可能犯的小错误。作为一个新手,我发现它非常有帮助。 :-)
  • 我安装了Visual Assist,将试用一个月,但是对于这个问题的问题,它没有帮助。 (我在顶部注释了#include ,保存并编译它并:dropbox.com/s/bd3my8l3r7bqcrj/DidntHelp.PNG?raw=1
  • 我很抱歉。我自己实际上使用了 Resharper,但很多人更喜欢使用 VAX(出于大型项目的性能原因,尽管我没有遇到任何问题),所以我想我也会提到它。我用 Resharper 检查了你的代码,它似乎确实把它捡起来了。 Here's a picture.
  • hm :),你提到了 ReSharper,但你链接到了 wholetomato.com :) 你的意思是链接到 jetbrains.com/resharper-cpp 对吗?
  • uuh,我安装了 resharper,但我对我的错误感到困惑。我看到的内容:dropbox.com/s/64verq3shjam969/What.PNG?raw=1,顶部的红色突出显示:“预编译的头文件必须包含在源文件的顶部”,底部:dropbox.com/sh/v77svb2aqdzme2a/AABAyZJ6CX5LhcQpqEjajchSa?raw=1 与您的 @notanalien 相比,您认为缺少什么?跨度>
【解决方案2】:

我遇到了这个错误

错误 C2676 二进制“

作为解决方案 我刚刚在定义类的头文件中使用了#include &lt;fstream&gt; (ie fstream)。 这对我有用。

【讨论】:

    【解决方案3】:

    BOBVec3d 更改为 Vec3D

    BOBVec3D(void) {}
    BOBVec3D(float x, float y, float z) : mX(x), mY(y), mZ(z) {}
    inline friend std::ostream& operator<< (std::ostream& os, const BOBVec3D& v);
    

    Vec3D(void) {}
    Vec3D((float x, float y, float z) : mX(x), mY(y), mZ(z) {}
    inline friend std::ostream& operator<< (std::ostream& os, const Vec3D& v);
    

    【讨论】:

    • 很抱歉,我将代码匿名化并错过了这些条目
    猜你喜欢
    • 2020-08-10
    • 2021-02-14
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 2021-06-11
    • 2020-10-10
    • 2020-12-20
    • 1970-01-01
    相关资源
    最近更新 更多