我想将类指针传递给另一个类的成员的函数,它将无法正常工作。如果函数fill_packet
不是任何类的成员,则代码编译不会出现问题:
// WORKS FINE:
class Packet{
private:
char *contents;
public:
void pack();
};
void fill_packet(Packet *a){
a->pack();
};
但是,如果函数
fill_packet
在另一个类(在此为Worker)中,则在我尝试访问a
方法时,它突然不再编译。// WON'T COMPILE:
// error: ‘Packet’ has not been declared
class Worker{
public:
void fill_packet(Packet *a){
a->pack();
};
};
class Packet{
private:
char *contents;
public:
void pack();
};
谁能给我见识?提前致谢
最佳答案
确保在Worker类之前定义了Packet类,这是一个完整的测试:
#include <iostream>
class Packet {
private:
char *contents;
public:
void pack() {
this->contents = "Some text";
}
char * getContents() {
return this->contents;
}
};
class Worker {
public:
void fill_packet(Packet *a) {
a->pack();
}
};
int main() {
Packet * packet = new Packet;
Worker worker;
worker.fill_packet(packet);
std::cout << packet->getContents() << std::endl;
delete packet;
return 0;
}
如果运行此测试,您将获得期望的输出。