类内部的结构

时间:2012-12-27 04:12:55

标签: c++ class struct member

我对将结构作为类成员的语法有一些疑问。

我有这个结构:

/*  POS.H   */
#ifndef POS_H
#define POS_H
struct pos{
    int x;
    int y;

    pos operator=(const pos& a){
        x=a.x;  y=a.y;
        return a;
    }

    pos operator+(const pos& a)const {
        return (pos){a.x+x,a.y+y};
    }

    bool operator==(const pos& a)const {
        return (a.x==x && a.y== y);
    }
};
#endif /* POS_H */

在另一个文件中有主要功能:

/* MAIN.CPP */
#include "pos.h"
#include "clase.h"
int main(){
    pos pos;
    pos.x=0;
    pos.y=0;
    clase clase();
}

然后,文件clase.h有3个不同的内容,其中包含class clase。

编译好:

#include "pos.h"
class clase{
    private:
        pos posi;
    public:
        clase(pos pos):posi(pos){};
};

这不编译(只是更改成员的名称):

#include "pos.h"
class clase{
    private:
        pos pos;
    public:
        clase(pos pos):pos(pos){};

这也很好编译(使用pos作为neme但使用关键字struct):

#include "pos.h"
class clase{
    private:
        struct pos pos;
    public:
        clase(struct pos pos):pos(pos){};
};

我的问题是:为什么这些代码会编译或不编译?

1 个答案:

答案 0 :(得分:1)

传统上,将成员命名为结构名称通常不是很好的编码实践,看起来编译器在尝试声明名为pos的私有成员时会感到困惑,除非您强制执行结构类型。

简而言之,它只是命名冲突,你应该习惯于命名成员与结构或对象名称略有不同。也许在TitleCase中命名您的结构和对象,然后在您的成员上使用camelCasing。在这个例子中,命名为struct POS,然后命名为private:POS mPos;