我怎样才能转发声明一个类并稍后在 c++ 中使用其成员功能
How can I forward declare a class and use its member funcions later in c++?
是否可以转发声明一个类,然后使用其成员功能?我正在尝试这样做:
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i){
s->setLine(i);
s->called(true);
}
int getX(){return x;}
}
class Second{
private:
int line=2;
bool cal=false;
public:
void setLine(int l){line = l;}
void called(bool b){cal=b}
bool interact(First* f){
if ((f->getX())>3)
return true;
else
return false;
}
}
我的实际问题有点复杂,功能做更多的事情,但我试图做的是让这两个类相互使用功能并让它们以这种方式交互。有谁知道是否有办法做到这一点?
是否可以转发声明一个类,然后使用其成员函数?
不,不是。在定义类之前,无法访问向前声明的类、变量、函数、枚举、嵌套类型等的任何成员。
在定义前向声明类之后,需要移动调用前向声明类的成员函数的函数的实现。
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i); // Don't define it here.
int getX(){return x;}
};
class Second{
...
};
// Define the function now.
void First::move(Second* s,int i){
s->setLine(i);
s->called(true);
}
你可以把First::move
的定义放在类之外,在Second
的定义之后。只有声明需要出现在First
的定义中。
实际上,您可以将First::move
的定义放在.cpp文件中,而不是放在任何标头中。
下面将为您解决问题,但最好将声明和实现分开。
class Second;
class First{
private:
int x=0;
public:
void move(Second* s,int i); //<- move implementation after Second's declaration
int getX(){return x;}
}
class Second{
private:
int line=2;
bool cal=false;
public:
void setLine(int l){line = l;}
void called(bool b){cal=b}
bool interact(First* f){
if ((f->getX())>3)
return true;
else
return false;
}
};
void First::move(Second* s,int i){
s->setLine(i);
s->called(true);
}
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 多态性和功能结合
- 带内存和隔离功能的SQLite
- 在CMakeLists.txt的安装功能中使用.cmake文件有什么用
- 类模板的成员功能的定义在单独的TU中完全专业化
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何在C++中获得"静态纯虚拟"功能?
- 两个文件使用彼此的功能-如何解决
- 我应该实现右值推送功能吗?我应该使用std::move吗
- QML按钮点击功能执行顺序
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 有没有可能有一个只有ADL才能找到的非好友功能
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 文件系统:复制功能的速度秘诀是什么
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 如何在Directwrite中获得给定字体的可用OpenType功能
- 对可变参数使用声明.如何选择正确的功能
- 询问在设计我的手臂模拟器功能表示格式1
- 功能原型的目的
- 这里在 Linux 中具有"CreatePipe"和"CreateProcessW"功能吗?