我定义了一个类:
#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 错误代码。我不确定我错过了什么。如何使用 vectors
和 ints
正确重载赋值运算符?
最佳答案
你不需要为你的类提供任何特殊的成员函数,因为在这种情况下编译器合成的会做正确的事情。最好的选择是从类定义中删除赋值运算符和复制构造函数。
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/