C++ 访问稍后在C+中定义的类的成员+;

C++ 访问稍后在C+中定义的类的成员+;,c++,C++,我得到一个错误: /Users/apple/Desktop/c.cpp:9:3: error: member access into incomplete type 'const World' w.name; ^ /Users/apple/Desktop/c.cpp:6:7: note: forward declaration of 'World' class World; ^ 1 error generated. 运行时: #包括 #包括 使用名

我得到一个错误:

/Users/apple/Desktop/c.cpp:9:3: error: member access into incomplete type 'const World'
        w.name;
         ^
/Users/apple/Desktop/c.cpp:6:7: note: forward declaration of 'World'
class World;
      ^
1 error generated.
运行时:

#包括
#包括
使用名称空间std;
阶级世界;
无效显示名称(const World&w){

cout您不能这样做。任何使用已声明但未定义的类都无法访问其内部或使用任何关于它们的知识,例如大小或布局。您可以使用
World*
World&
,但不能以任何方式取消引用它们

处理这种情况的常用方法是在头文件中定义类。该定义必须定义所有成员变量和声明成员函数,但不需要定义这些函数。现在编译器知道类的内部结构并可以相应地使用它

下面是一个示例,说明类的可见性如何影响您对它的操作

class World;

void func(const World& w) {
    std::cout << w; // Okay, only uses reference
    std::cout << w.name; // error
    World w2 = w1; // error, compiler needs to know that class offers copy constructor
    w.do_something(); // error, compiler doesn't know what this is
}

class World {
public:
    std::string name;

    void do_something() const; // Doesn't need implementation to be called
}

std::ostream& operator<<(std::ostream s, const World& w) {
    std::cout << w.name; // OK
    w.do_something(); // OK
    return s;
}
阶级世界;
无效函数(const World&w){

std::cout您不能这样做。任何使用已声明但未定义的类都不能访问其内部或使用其任何知识,例如大小或布局。您可以使用
World*
World&
,但不能以任何方式取消引用它们

处理这种情况的常用方法是在头文件中定义类。该定义必须定义所有成员变量和声明成员函数,但不需要定义这些函数。现在编译器知道类的内部结构并可以相应地使用它

下面是一个示例,说明类的可见性如何影响您对它的操作

class World;

void func(const World& w) {
    std::cout << w; // Okay, only uses reference
    std::cout << w.name; // error
    World w2 = w1; // error, compiler needs to know that class offers copy constructor
    w.do_something(); // error, compiler doesn't know what this is
}

class World {
public:
    std::string name;

    void do_something() const; // Doesn't need implementation to be called
}

std::ostream& operator<<(std::ostream s, const World& w) {
    std::cout << w.name; // OK
    w.do_something(); // OK
    return s;
}
阶级世界;
无效函数(const World&w){

这就是为什么要将整个类定义放在所有方法实现之前包含的头文件中。“但是如果我想访问稍后定义的类的成员,并且坚持在类定义之前定义此调用函数,该怎么办?”-不行。可能是XY问题。@尼尔·巴特沃斯谢谢你提醒,我已经把这个问题做得更恰当了。这就是为什么你把整个类定义放在所有方法实现之前包含的头文件中。“但是,如果我想访问稍后定义的类的成员,并且我坚持在定义该类之前定义此调用函数,该怎么办”-您不能。可能存在XY问题。@NeilButterworth感谢您的提醒,我已经把这个问题做得更恰当了。