构造函数和运算符不起作用

Constructors and operators in not working

本文关键字:不起作用 运算符 构造函数      更新时间:2023-10-16

我正在尝试学习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"

我做错了什么?

你需要一个构造函数来wchar_t*

String(const wchar_t*);

"main中的某个地方"的三行都没有使用赋值,所以我们可以忽略您可能已定义的任何赋值运算符。而且您还没有定义转换构造函数,它需要单个参数(wchar_t const* ),以转换您的wchar_t const*