标头和源类文件不起作用

Header and source class file not working

本文关键字:文件 不起作用      更新时间:2023-10-16

我有一个基本的程序正在运行,但是当我尝试创建头文件和类文件时,我没有成功。我想知道是否有人可以查看我的代码并查看我出错的地方。我正在使用Linux上的文本编辑器并使用G ++进行编译。

向下.h

#ifndef down_h
#define down_h
#include <string>
class down{
//function of web page retreival
private:
void write_data(char *ptr, size_t size, size_t nmemb, void *userdata) {
}
//webpage retrieval
public:
down();
std::string getString(const char *url){
}
};
#endif

向下.cpp

#define CURL_STATICLIB
#include <stdio.h>
#include <curl/curl.h> 
#include <curl/easy.h>
#include <string>
#include <sstream>
#include "down.h"
using namespace std;
//function of web page retreival
size_t write_data(char *ptr, size_t size, size_t nmemb, void *userdata) {
std::ostringstream *stream = (std::ostringstream*)userdata;
size_t count = size * nmemb;
stream->write(ptr, count);
return count;
}
//webpage retrieval
std::string getString(const char *url){
CURL *curl;
FILE *fp;
std::ostringstream stream;
CURLcode res;
char outfilename[FILENAME_MAX] = "bbb.txt";
curl = curl_easy_init();
if (curl) {
fp = fopen(outfilename,"wb");
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &stream);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
fclose(fp);
}
return stream.str();
}

主.cpp

#include "down.h"
#include <iostream>
int main(void) {
    const char *url = "www.google.com";
    std::cout << getString("www.google.com");
    return 0;
}

使用以下代码:

void write_data(char *ptr, size_t size, size_t nmemb, void *userdata) { }

在标头 down.h 文件中,您正在实现该函数,该函数不执行任何操作,使其成为内联无用的方法。你在向下.cpp再做一次,但你不能这样做。

您的代码在 down.h 头文件中应如下所示:

void write_data(char *ptr, size_t size, size_t nmemb, void *userdata);

另一方面,在你的 down.cpp 中,你有很多错误:当你想在 cpp 源文件中实现一个方法时,你必须明确指出该方法是类 down 的一部分(应该写成大写的 Down),使用 scope 运算符:

size_t down::write_data(char *ptr, size_t size, size_t nmemb, void *userdata) {
    std::ostringstream *stream = (std::ostringstream*)userdata;
    size_t count = size * nmemb;
    stream->write(ptr, count);
    return count;
}

您的getString方法也是如此。您还有其他错误,例如,在头文件中声明默认构造函数,但未实现它。

我真的建议您阅读一本书或观看有关OOP的其他教程C++,因为看起来您真的没有这样做。您还以危险的方式使用了太多 C/C++(指针)的功能......