c++ - 用类和 vector 重载赋值运算符

标签 c++ vector operator-overloading

我定义了一个类:

#ifndef _STRINGCLASS_H
#define _STRINGCLASS_H
using namespace std;

#include <iostream>
#include <vector>

class String {
protected:
    int length;
    vector<string> buf;

public:
    String();
    String(const char* input);
    String(char input);
    String(int input);
    String(const String& input);
    String(char input, int input2);

    String& operator=(const String& input);


};

#endif

并试图通过这样的方式重载赋值运算符:

String& operator=(const String& input) {

    buf = input.buf;
    length = input.length;

    return *this;
}

我得到了 buf protected 和 length protected 错误代码。我不确定我错过了什么。如何使用 vectorsints 正确重载赋值运算符?

最佳答案

你不需要为你的类提供任何特殊的成员函数,因为在这种情况下编译器合成的会做正确的事情。最好的选择是从类定义中删除赋值运算符和复制构造函数。

class String 
{
protected:
    int length;
    vector<string> buf;

public:
    String();
    String(const char* input);
    String(char input);
    String(int input);
    String(char input, int input2);
};

关于c++ - 用类和 vector 重载赋值运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131062/

相关文章:

c++ - 如何使用 vector 默认构造函数?

c++ - vector : rend() is being invalidated by erase()

c++ - operator new 重载c++,处理失败无一异常(exception)

Lua 5.3 使用 debug.setmetatable 覆盖整数值的 ~ (__bnot) 运算符

c++ - 使用模板的事件处理

c++ - 如何使用 Qt "Reveal in Finder"或 "Show in Explorer"

c++ - 无法从 C++ 中的 vector 中删除 void 指针

c++ - 重载运算符+/char* ch1 + char* ch2

c++ - 难以在C++中读取文件

c++ - ICC 中的 -O3 搞乱了内在函数,与 -O1 或 -O2 或相应的手动组装一起使用