【问题标题】:Header and source class file not working头文件和源类文件不起作用
【发布时间】:2014-12-31 22:00:21
【问题描述】:

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

down.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();
}

main.cpp

#include "down.h"
#include <iostream>

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

【问题讨论】:

  • 不要在头文件中给你的函数一个空的主体。
  • 请学习如何缩进你的代码。我不在乎你使用什么缩进方案,但一定要用一个。

标签: c++ class header g++


【解决方案1】:

使用以下代码:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    相关资源
    最近更新 更多