如何使用const char *和/或字符串重载operator =?

时间:2018-11-17 17:31:29

标签: c++ string char operator-overloading assignment-operator

我已经搜索了这类问题,但是我仍然不明白为什么我的代码有错误以及如何实现...

我想做的是创建一个类,该类可以由string和char *分配,就像std :: string ... http://www.cplusplus.com/reference/string/string/operator=/

  • string(1)string&operator =(const string&str);
  • c-string(2)string&operator =(const char * s);

我会写

string str1 = "haha"; //way(2)
string str2 = str1; //way(1)

所以,我写了这个课...

class LinkedList
{
private:
    ListNode *first;
public:
    LinkedList():first(nullptr) {};
    LinkedList(const string &str);
    LinkedList& operator=(const string &str);
    LinkedList& operator=(const char *s);
    void Print_LinkedList();
    void Push_back(char c);
//    void Insert();
//    void Delete();
//    void Invert();
//    void Clear();
};

而且,方法部分是...

LinkedList& LinkedList::operator=(const string &str)
{
    if (str.length()%3 != 1)//legal string_input.length is 3n+1
    {
        cout << "LinkedList building error" << endl;
    }
    else
    {
        for (unsigned int i = 0; i < str.length(); i+=3)
        {
            this->Push_back(str.at(i));
        }
    }
    return *this;
}

LinkedList& LinkedList::operator=(const char *s)
{
//    if (???) //please give me some suggestions...
//    {
//        cout << "LinkedList building error" << endl;
//    }
//    else
//    {
//        for (???) //please give me some suggestions...
//        {
//            this->Push_back(???); //please give me some suggestions...
//        }
//    }
    this->Push_back('x');
    return *this;
}

而且,主要部分是...

int main()
{
    LinkedList linkedlist1;
    linkedlist1.Push_back('x');
    linkedlist1.Push_back('a');
    linkedlist1.Print_LinkedList();

    string str_test = "H->a";
    LinkedList linkedlist2(str_test);
    linkedlist2.Print_LinkedList();

    string str_test2 = "H->A->h->o";
    LinkedList linkedlist3 = str_test2;
    linkedlist3.Print_LinkedList();

    LinkedList linkedlist4 = "x"; //there's an error in this line
    linkedlist4.Print_LinkedList();

    return 0;
}

然后,编译器说,

"error: conversion from 'const char [2]' to non-scalar type 'LinkedList' requested|"

你能告诉我...

  

1。为什么我的代码有编译器错误?
  2.如何解决该错误?
  3.在“ LinkedList&LinkedList :: operator =(const char * s){//我应该在这里写什么}”中实现的一些建议

感谢您的帮助。

0 个答案:

没有答案