【发布时间】:2013-09-29 15:03:31
【问题描述】:
我有一个名为person.lib 的第三方库及其标头person.h。这是我的实际项目结构,它可以完美地编译和运行。
实际结构:
main.cpp
#include <iostream>
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
using namespace person;
using namespace std;
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
我想通过将Client 类的声明与其定义分开并创建client.h 和client.cpp 来重构我的代码。 注意:sayHello() 和 onMessage(const * char const) 是 person 库的函数。
重构结构:
main.cpp
#include <iostream>
#include "client.h"
using namespace person;
using namespace std;
int main()
{
try
{
Person *p = new Client;
p->sayHello();
}
catch(Exception &e)
{
cout << e.what() << endl;
return 1;
}
return 0;
}
client.cpp
#include "client.h"
using namespace person;
using namespace std;
Client::Client() {
char str[11];
gen_random(str, 10);
this->setName(str);
}
void Client::onMessage(const char * const message) throw(Exception &)
{
cout << message << endl;
}
void Client::gen_random(char *s, const int len) {
//THIS FUNCTION GENERATES A RANDOM NAME WITH SPECIFIED LENGTH FOR THE CLIENT
}
client.h
#ifndef CLIENT_H
#define CLIENT_H
#include <time.h>
#include <ctype.h>
#include <string>
#include "person.h"
class Client : public Person
{
public:
Client();
void onMessage(const char * const);
private:
void gen_random(char*, const int);
};
#endif
如您所见,我只是创建了一个 client.h,其中包含了基类 person.h,然后我创建了 client.cpp,其中包含了 client.h 和定义的功能。现在,编译给了我这些错误:
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2440: 'inizialization': unable to convert from 'Client *' to 'person::impl::Person *' main.cpp 15 1 Test
error C2504: 'Person': base class undefined client.h 7 1 Test
error C2039: 'setName': is not a member of 'Client' client.cpp 8 1 Test
error C3861: 'sendMessage': identifier not found client.cpp 34 1 Test
这只是一个剪切和复制重构,但它不起作用,我真的不明白为什么!解决方案是什么,为什么它会给我这些错误?有什么我缺少的关于 C++ 结构的东西吗?
【问题讨论】:
-
在重构的标头中包含
<person.h>,但在原始代码中是"person.h"也许链接器没有找到它? -
@jnovacho 是转录错误,改正后还是一样。
-
client.h 不使用 person 的命名空间。
标签: c++ compilation header