2012-11-27 61 views
1

我想学习C++,我不明白为什么下面的代码不工作:构造和C++运算符 - 不工作

class String 
{ 
public: 
    String(); 
    String(const String& other); 
    String& operator = (const String& other); 
    String& operator = (const wchar_t* other); 
    String& operator() (const wchar_t* other); 
    ~String(); 
    operator const wchar_t*(); 
      ... 

某处在主要功能:

wchar_t* x = L"A test string"; 
String y = (String)x; //not working 
String z = x; //not working 

的VC++编译器告诉我:

Error 1 error C2440: 'type cast': cannot convert from 'wchar_t *' to 'String' 
Error 2 error C2440: 'initializing': cannot convert from 'wchar_t *' to 'String'  
IntelliSense: no suitable constructor exists to convert from "wchar_t *" to "String" 

我在做什么错?

回答

6

你需要一个构造函数wchar_t*

String(const wchar_t*); 
+1

详细说明:赋值运算符不足。这只会用于赋值('String y; y = x;')。初始化不是赋值,即使它使用相同的“=”符号。 – hvd

3

无三线“在主某处”使用分配的,所以 我们可以忽略你可能已经定义的任何赋值运算符。 而你还没有定义一个转换构造函数,它需要一个 单参数(一个wchar_t const*)来转换你的wchar_t const*

+0

第一句话+1。 –