C++类声明错误?
问题描述:
家伙,我是新来的C++ 我想创建一个类这些都是我的文件C++类声明错误?
//main.cpp
#include <iostream>
#include "testing/test.h"
#include <string>
using namespace std;
int main(void)
{
test c;
c.set_url("e");
}
test.h
#ifndef TEST_H_
#define TEST_H_
#include<string>
class test {
public:
void testing(string url);
};
#endif /* TEST_H_ */
//test.cpp
#include <iostream>
#include<string>
using namespace std;
void crawl::testing (string url) {
cout<< "i am from test class";
}
我收到错误:“串”尚未声明错误
答
问题是您需要使用完全限定名称string
,因为std
名称空间未导入
class test {
public:
void testing(std::string url);
};
请避免通过在testing.h文件中使用std
名称空间来解决此问题的诱惑。这通常是不好的做法,因为它可以改变名称解析的方式。在头文件中限定名称更安全,虽然有点烦人。
答
你得到的错误是从头文件ie中不使用名称空间std。 std::string
,并且在包含头文件(或头文件)之前没有using namespace std;
。
命令using namespace std;
是说假设一个类可以在这个命名空间中,但它只适用于该命令之后的所有用途。
如果你这样做,它也会工作,虽然一般来说这是不好的形式。
#include <string>
using namespace std;
#include "testing/test.h"
此外,不要忘记包含test.h到test.cpp。