c++ - header 和源类文件不起作用

标签 c++ class header g++

我运行了一个基本程序,但是当我尝试创建头文件和类文件时却没有成功。我想知道是否有人可以查看我的代码,看看我哪里出错了。我在 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) {

在 header down.h 文件中,您正在实现该函数,该函数什么也不做,使其成为inline。无用的方法。您在 down.cpp 中再次执行此操作,但您无法执行。

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

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

在你的 down.cpp 中,另一方面,你有很多错误:当你想在 cpp 源文件中实现一个方法时,你有具体来说,该方法是类 down 的一部分(应该写成大写的 Down),使用 scope operator :

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 方法也是如此。您还有其他错误,例如,在头文件中您声明了默认构造函数,但您没有实现它。

我真的建议你读一本书或看一些其他的tutorials在面向 C++ 的 OOP 上,因为看起来你真的没有做过。您还以危险的方式使用了太多的 C/C++(指针)功能......

关于c++ - header 和源类文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27726700/

相关文章:

c++ - 对类成员线程的双冒号访问 (::) 是否安全?

c++ - 在 C++ 中对数组使用运算符减号 (-)

Python 类共享变量给出了意外的输出

php类在函数内调用函数

PHP: get_headers 设置临时 stream_context

c++ - 修复基于模块的库中的自阻塞包含

c++ - C++ 中的侵入式与非侵入式引用计数指针

java - 在java中使用 'this'关键字和扩展类

html - 坚持使用标题的 CSS 宽度/ float

c++ - "Extra Qualification on Member"模板类错误