我得到了错误:
/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.
运行时:
#include <string>
#include <iostream>
using namespace std;
class World;
void show_name(const World& w) {
cout << w.name << endl;
return;
}
class World {
public:
string name;
};
下面的链接提供了使用后面定义的类类型的方法,
Defining a class member with a class type defined later in C++
但是,如果我想访问稍后定义的类的成员并且我坚持在类的定义之前定义这个调用函数,就像我使用的示例一样。
最佳答案
你不能那样做。对已声明但未定义的类的任何使用都不能访问其内部或使用它们的任何知识,例如大小或布局。您可以使用 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;
}
请注意,World::do_something()
需要在某处定义,但它甚至可以是一个单独的翻译单元。这种机制允许在 .h 文件中定义类,并在 .cpp 文件中定义它们的方法。如果整个项目中不存在定义,则不会出现编译器错误,但会出现链接器错误。
关于c++ - 访问稍后在 C++ 中定义的类的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540109/