c++ - 从类中返回结构映射(结构定义在类中): compile error

标签 c++ class struct

我有一个类,在该类中我定义了一个结构。该结构具有重载的比较运算符,因此它可以与映射一起使用(以 int 作为键)。

在处理类之前,我在 .cc 文件中定义了结构,该文件还包含一个返回该结构映射的函数。它奏效了。

现在我想在类头中定义结构,并且该类应该有一个返回结构映射的函数。

这是我的代码的简化版本,编译时出现与完整版本相同的错误。我不明白这个错误,非常感谢任何帮助!

干杯。

myclass.h:

#include <map>

class myclass {
  public:
    struct mystruct {
      int i;
      mystruct();
      mystruct(int j);

      bool operator==(const mystruct& rhs);
      bool operator>(const mystruct& rhs);
      bool operator<(const mystruct& rhs);
    };

    ::std::map<int,mystruct> getStructMap();
};

myclass.cc:

#include <map>
#include "myclass.h"

myclass::mystruct::mystruct(int j) : i(j) {};
myclass::mystruct::mystruct() : i(-1) {};

bool ::myclass::mystruct::operator==(const ::myclass::mystruct& rhs) {return i==rhs.i; }
bool ::myclass::mystruct::operator>(const ::myclass::mystruct& rhs) {return i>rhs.i; }
bool ::myclass::mystruct::operator<(const ::myclass::mystruct& rhs) {return i<rhs.i; }


::std::map<int,::myclass::mystruct> ::myclass::getStructMap() {
  ::std::map<int,::myclass::mystruct> structMap;
  for (int i=0;i<5;i++) structMap[i]=::myclass::mystruct(i);
  return structMap;
}

我的程序.cc:

#include <iostream>
#include <map>
#include "myclass.h"

int main() {    
  myclass myobj;
  ::std::map<int,::myclass::mystruct> mymap;
  mymap=myobj.getStructMap();   
}

编译错误:

> g++ -o myprogram myprogram.cc myclass.cc
myclass.cc:12: error: ‘class std::map<int, myclass::mystruct, std::less<int>,std::allocator<std::pair<const int, myclass::mystruct> > >::myclass’ has not been declared
myclass.cc:12: error: ISO C++ forbids declaration of ‘getStructMap’ with no type
myclass.cc: In function ‘int getStructMap()’:
myclass.cc:15: error: cannot convert ‘std::map<int, myclass::mystruct, std::less<int>, std::allocator<std::pair<const int, myclass::mystruct> > >’ to ‘int’ in return

最佳答案

当前您的代码解析为

/*missing type*/ ::std::map<int,::myclass::mystruct>::myclass::getStructMap()

因此,第一个错误,map 没有 myclass 成员(或子类、方法、typedef,...) 然后是第二个错误:没有返回类型(因此假设 int,因此转换错误)。

因此,为了解决这个问题,在 myclass.cc 中,您可以删除多余的 ::,如下所示:

::std::map<int,::myclass::mystruct> myclass::getStructMap() {

或添加额外的括号:

::std::map<int,::myclass::mystruct> (::myclass::getStructMap()) {

关于c++ - 从类中返回结构映射(结构定义在类中): compile error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24130902/

相关文章:

c++ - 类成员函数作为函数指针

ruby-on-rails - 无法在 Rails 应用程序的 lib 文件夹中使用定义的类

c - 从函数导出列表

java - 将字节数组分配给 Java 对象

c++ - 抽象类的大小是多少?为什么我们不能创建抽象类的对象?

c++ - 堆栈上的最大激活记录

来自自定义类的 Swift addChild

c - 对结构使用 malloc 时出错

python - Cython:在 DLL 中注册用于回调的 Python 函数

c++ - Xcode 调试器找不到我的文件