错误:使用std::cout在类作用域中为非成员使用声明

error: using-declaration for non-member at class scope using std::cout

本文关键字:成员 声明 作用域 std 使用 cout 错误      更新时间:2023-10-16

我下载了一个c++项目,并能够使用cmake生成的makefile进行编译。

然而,当我试图在项目的一个.hh文件中添加我自己的一系列.h文件时,我开始遇到一百万个错误,其中之一是:

错误:在类作用域中使用非成员的声明使用std::cout;

当包含的.h文件using std::cout在其他地方使用,但添加到该项目中时会出现此错误。

问题出在哪里?

using std::cout;
using std::endl;
class TextManager : public FileManager {
    public:
        TextManager (const char * filename);
        void scanFile (Image &image, Scene &scene);
        void scanObjectModel (Image &image, Scene &scene);
        void getImageData (Image &image);
        void getMaterialData (Scene &scene);
        void getLightData (Scene &scene);
        void getSphereData (Scene &scene);
        void getPlaneData (Scene &scene);
        void getTriangleData (Scene &scene);
        int getLineValue (int size);
        void getLineValue2 (float (&lineNumbers) [10], Scene &scene, int &lineNumbersIndex);
        void getVerticesValues (int initPos, Scene &scene);  
        private:
   std::string line;
   float fractionaryTenPowers [6];
};

问题解决了。是因为缺少一个括号来关闭导致它的类之一的声明。

错误意味着您已经完成了以下操作:

struct Foo {
  using std::cout;
  ...
};

这是无效的C++,在类主体中,您只能为基类的成员添加using声明,而不能添加任意名称。

只能在命名空间范围或函数体内部添加using std::cout

只要将它放在publicprivate部分下,就可以将其放在类中。

#include <iostream>
namespace CoolNamespace
{
  struct AnotherReallyLongClassName
  {
    int a = 75;
  };
  struct SomeReallyLongClassName
  {
    int a = 42;
  };
} // namespace CoolNamespace
class Widget
{
  // You can't do this though!
  // using ShorterName = CoolNamespace::SomeReallyLongClassName;
  public:
    // You can use a using statement inside of a class!
    using ShorterName = CoolNamespace::SomeReallyLongClassName;
    ShorterName foo;
    int get_another_name()
    {
      return bar.a;
    }
  private:
    // You can do it here also!
    using AnotherName = CoolNamespace::AnotherReallyLongClassName;
    AnotherName bar;
};
int main()
{
  Widget widget;
  std::cout << widget.foo.a << std::endl;
  // Also, if you can reference public using statements from the class definition.
  Widget::ShorterName thing;
  std::cout << thing.a << std::endl;
  // But you can't do this because it's private.
  // Widget::AnotherName name;
  return 0;
}

实际上,请检查类声明中的某个成员函数中是否有一个开括号。

我是在.h文件中完成的;

class foo{
    void cat();
    void bar{
    void dog();
}
in .cc file I defined the member functions
void foo::cat(){
    std::cout<<"This is cat"<<std::endl;
}
void foo::bar(){
    std::cout<<"hello"<<std::endl;
}
void foo::dog(){
    std::cout<<"meow"<<std::endl;
}

但请注意,我在.h文件中使用了{而不是;作为成员功能栏。这导致了错误。(至少对我来说).