2015-09-22 40 views
0

的initalisation錯誤這是我process.cpp獲取用於構造

#include<iostream> 
    #include "process.h" 
    #include "CString.h" 
    void process(const char* s){ 
    w1::Cstring cs(s); 
    std::cout << cs; 
    } 

我CString.h

#ifndef _CSTRING_H 
#define _CSTRING_H 
#include<iostream> 
namespace w1{ 
const int CHAR_NUM=3; 
class Cstring{ 
public: 
    char str[CHAR_NUM+1]; 
    Cstring(char* s); 
    void display(std::ostream& os) const; 

}; 
std::ostream& operator<<(std::ostream&os ,const Cstring& cs); 
} 
#endif 

這是我CString.cpp

#include <iostream> 
#include "CString.h" 
namespace w1{ 
Cstring::Cstring(char* s){ 
    if (s=='\0'){ 
     str[0]='\0'; 
    }else{ 
     for (int i=0;i<CHAR_NUM;i++){ 
      str[i]=s[i]; 
      str[i+1]='\0'; 
     } 
    } 
} 
void Cstring::display(std::ostream& os) const{ 
    os<<str<<std::endl; 
} 

std::ostream& operator<<(std::ostream&os ,const Cstring& cs){ 
    cs.display(os); 
    return os; 
} 
} 

我我得到一個錯誤,說我沒有任何匹配的構造函數初始化在process.cpp中的w1 :: CString 我不dont知道如何糾正它。

+0

該構造函數應該採用'const char *'。 (它也以其他方式破壞。) –

回答

1

建議將構造函數的參數類型改爲const char *,而不是修改參數,如代碼中所示。如您的代碼所示,編譯器允許隱式地將非const轉換爲const,但不能如其他方式轉換。

4

你寫了你的構造函數Cstring(char* s);作爲一個非const指針。但是你的函數void process(const char* s)正試圖傳遞一個const指針。編譯器不會自動拋棄const(出於好的原因)。

但是由於它們的構造似乎並沒有被修改其參數,你應該把它變成一個const指針:

Cstring(const char* s); 

因而認爲錯誤將得到解決。

+0

建議 - 「指向const的指針」而不是「const指針」。 – owacoder