通过c ++中的赋值初始化自己的String类

LPr*_*Prc 1 c++ string class

我正在StringEx用c ++ 编写我自己的字符串类(不用担心,只是为了练习)但是我没有通过为其分配字符串来创建我的类的实例:

StringEx string1 = StringEx("test"); // works fine
StringEx string2 = "test"; // doesn't work

string string3 = "test";
string1 = string3; // also works fine
Run Code Online (Sandbox Code Playgroud)

我重载了赋值运算符,所以它可以处理,std::string但我必须先创建一个对象StringEx.

如何通过为其StringEx指定字符串来创建新对象?甚至可以将c ++ "string"作为我的StringEx类的对象进行处理吗?

这是我StringEx.h 现在的作品

#ifndef STRINGEX_H
#define STRINGEX_H


#include <iostream>
#include <string>
#include <vector>
using namespace std; //simplyfying for now

class StringEx
{
private:
    vector<char> text;
public:
    StringEx();
    StringEx(string);
    StringEx(const char*);  // had to add this
    StringEx(vector<char>);

    int size() const;
    int length() const;
    char at(int) const;

    void append(const string&);
    void append(const StringEx&);
    void append(const char*);  // had to add this

    StringEx operator+(const string&);
    StringEx operator+(const StringEx&);
    StringEx operator+(const char*);  // had to add this too

    StringEx operator=(const string&);
    StringEx operator=(const StringEx&);
    StringEx operator=(const char*);  // had to add this too

    StringEx operator+=(const string&);
    StringEx operator+=(const StringEx&);
    StringEx operator+=(const char*);  // had to add this too

    friend ostream& operator<<(ostream&, const StringEx&);
};

#endif // STRINGEX_H
Run Code Online (Sandbox Code Playgroud)

JBL*_*JBL 5

一些准确性:

StringEx string1 = StringEx("test"); // works fine
Run Code Online (Sandbox Code Playgroud)

这使用了复制构造函数,即 StringEx(const StringEx& other);

StringEx string2 = "test"; // doesn't work
Run Code Online (Sandbox Code Playgroud)

这会尝试使用具有以下签名的构造函数: StringEx(const char* str);

最后,那两行:

string string3 = "test";
string1 = string3; // also works fine
Run Code Online (Sandbox Code Playgroud)

创建一个std::stringconst char*,其标准库定义,然后使用拷贝赋值运算符重载std::string,你似乎已经正确定义,即StringEx& operator=(const std::string& other).

这里的关键点是这句话:

Type myVar = something;
Run Code Online (Sandbox Code Playgroud)

它不是一个分配,它是一个变量的声明和初始化,它使用构造函数,而不是复制赋值运算符.

在你的情况下,你只是缺少一个带参数的构造const char*函数.