首先,我想为我的代码质量道歉,我只是在学习。我有一个大学作业。
字符串连接和添加一个字符到一个字符串(如在左边和右边)。实现使用重载操作符。
问题是这样的:我需要实现两个重载(operator+)首先:将一个元素添加到向量(+"e", 例如)。第二:向向量的开头添加元素(例如,"e"+)。
为了实现作业的第二部分,我遇到了问题。我在stackoverflow上搜索了类似的问题,但它们对我没有多大帮助。
下面是我的代码:
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class String
{
private:
public:
vector<T> ptr_string;
String() // default value constructor (empty string)
{
ptr_string.push_back('\0');
}
String(const String& other) // copy constructor of the same type
{
int n = other.getLength();
for (int i = 0; i < n; i++)
{
ptr_string.push_back(other.ptr_string[i]);
}
}
String(T symbol, int n) // n times repeated value constructor
{
for (int i = 0; i < n; i++)
{
ptr_string.push_back(symbol);
}
}
String(String&& a) // move constructor
: ptr_string(a.ptr_string)
{
a.ptr_string = nullptr;
}
int getLength() const
{
return ptr_string.size();
}
void printString() const
{
int i = 0;
for (int i = 0; i < ptr_string.size(); i++)
{
cout << ptr_string[i];
}
cout << endl;
}
template <typename T2>
auto operator+(T2 b)
{
ptr_string.push_back(b);
return ptr_string;
}
auto operator+(String const& a)
{
ptr_string.push_back(a);
return ptr_string;
}
};
int main()
{
String<char> P = String<char>('P', 10);
P + 'e';
P.printString();
'e' + P;
P.printString();
}
我试图将对向量的引用作为参数传递,但遇到了一个问题,这很可能不是正确的解决方案。
auto operator+( String const& a)
{
ptr_string.push_back(a);
return ptr_string;
}
String<char> P = String<char>( 'P', 10);
'e' + P;
P.printString();
预期结果:第一个月
2条答案
按热度按时间qybjjes11#
首先,
operator+
不应该修改当前对象,它不应该返回一个向量,而应该返回一个新的String<T>
,它应该是const
。你的
char,int
构造函数没有添加一个空终结符。也许这是故意的,但是我改变了它,因为我正在使用那个构造函数。此外,我删除了移动构造函数,因为它还不需要。在它的实现中,你把nullptr
赋给了vector
,这是错误的。你不需要实现移动构造函数,你可以声明它为=default;
,这也是我对复制构造函数所做的,因为编译器生成的复制构造函数和你自己写的一样好(或者更好)。然后,在你的代码中没有
+
对应'e'+String
。当作为成员实现时,this
总是左操作数。你可以把它作为自由函数实现。Demo
这只是对你代码的最小改动。我实际上也会把类外的其他操作符实现为自由函数。
char,int
构造函数中的循环应该用适当的向量构造函数替换,也许还有更多可以改进的地方。关于操作符重载的更多信息,我推荐你参考https://en.cppreference.com/w/cpp/language/operators和What are the basic rules and idioms for operator overloading?nbewdwxp2#
我不认为你的赋值真的涵盖了现实生活中发生的场景。它充满了代码的味道。正如@463035818_is_not_a_number提到的运算符+通常不修改当前对象。但它在技术上是可能的,见下文。向量并不意味着“push_front”,避免“push_front "向量作为一个一般规则(这里,我使用双端队列作为ex)。