2014-12-31 30 views
0

我得到了一個基本的程序運行,但當我嘗試創建一個頭文件和類文件時,我沒有成功。我想知道是否有人可以看我的代碼,看看我哪裏出錯了。我正在Linux上使用文本編輯器並使用G ++進行編譯。標題和源類文件不工作

down.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; 
} 
+2

不要在頭文件中給函數一個空的主體。 – Unimportant

+2

請了解如何縮進代碼。我不在乎你使用的是什麼縮進方案,但是使用一個。 –

回答

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源文件中的方法,你必須明確地說,該方法是類(應該寫大寫)的一部分,使用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方法也可以這麼說。例如,在聲明默認構造函數的頭文件中也有其他錯誤,但是您沒有實現它。

我真的推薦你閱讀一本書或者在OOP上看其他的tutorials for C++,因爲它看起來好像還沒有做到。您還以危險的方式使用C/C++(指針)的功能太多......