代码之家  ›  专栏  ›  技术社区  ›  Karl Antoun

错误C2011,尝试了此处已要求的所有内容[重复]

  •  -1
  • Karl Antoun  · 技术社区  · 3 年前

    我是Cpp的新手,有以下错误:

    Error   C2011   'point2d': 'struct' type redefinition
    

    这是我第一次使用模块,我的头出现了一个错误。这是我的代码:

    方形细胞。复写的副本:

    #include <vector>
    #include "squarecell.h"
    
    using namespace std;
    
    struct point2d {
    
        point2d(int x, int y) {
            X = x;
            Y = y;
        }
        point2d() {
            X = 0;
            Y = 0;
        }
        int X;
        int Y;
    };
    

    方形细胞。h:

    #pragma once
    
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    struct point2d {
        point2d(int x, int y);
        point2d();
        int X;
        int Y;
    };
    

    我在标题中尝试了这个:

    #pragma once
    
    #include <iostream>
    #include <vector>
    
    using namespace std;
    
    #ifndef point2d_HEADER
    #define point2d_HEADER
    
    struct point2d {
        point2d(int x, int y);
        point2d();
        int X;
        int Y;
    };
    #endif
    

    也没用,我到处找,我知道我做错了什么,但我想不出来。

    任何帮助都将不胜感激,

    卡尔

    2 回复  |  直到 3 年前
        1
  •  1
  •   POBIX    3 年前

    问题出现在源文件中,而不是标题中。

    实现过程如下:

    point2d::point2d(int x, int y) { ... }
    

    不是这样的:

    struct point2d {
        point2d(int x, int y) { ... }
    };
    
        2
  •  0
  •   Vlad from Moscow    3 年前

    你定义了结构 struct point2d 好几次。

    首先,它是在标题中定义的 "squarecell.h" 然后它至少在模块中被重新定义 squarecell.cc .

    只在页眉中保留结构定义,并在重新定义结构的每个模块中删除结构定义。而是在需要结构定义的每个模块中包含标题。

    构造函数可以在标题中的结构定义中定义(在本例中,它们将是内联函数),也可以只在一个模块中定义,如

    #include "squarecell.h"
    
    point2d::point2d(int x, int y) : X( x ), Y( y ) 
    {
    }
    point2d::point2d() : X(), Y()
    {
    }