如何让 + 重载在另一个文件C++中被识别?

How do you get a + overload to become recognised in another file C++?

本文关键字:C++ 识别 文件 另一个 重载      更新时间:2023-10-16

最近刚开始学习C++,我正在尝试从头开始制作自己的字符串类。我目前正在通过重载 += 和 + 运算符来连接字符串。在阅读了这篇文章,运算符重载的基本规则之后,我想出了以下实现;

String & String::operator+=(const String &o) 
{
char * newBuffer = new char[this->size() + o.size() - 1];
//copy over 'this' string to the new buffer
int index = 0;
while (this->at(index) != 0x0)
{
*(newBuffer + index) = this->at(index);
index++;
}
//copy over the param string into the buffer with the offset 
//of the length of the string that's allready in the buffer
int secondIndex = 0;
while (o.at(secondIndex) != 0x0)
{
*(newBuffer + index + secondIndex) = o.at(secondIndex);
secondIndex++;
}
//include the trailing null
*(newBuffer + index + secondIndex) = 0x0;
//de-allocate the current string buffer and replace it with newBuffer
delete[] this->s;
this->s = newBuffer;
this->n = index + secondIndex;
return *this;
}
inline String operator+(String lhs, const String &rhs)
{
lhs += rhs;
return lhs;
}

但是,编译器不会识别 + 重载!如果我将函数放在主测试文件(我调用该方法的位置(中,它确实有效,但如果将其放在所有其他方法所在的 String.cpp 文件中,则不起作用。

如果您需要,这是我的 String.h 文件;

#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int     size() const;
char    at(int i) const;
String  &operator+=(const String &o);
private:
char *  s;
int     n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be 
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};

感谢您的任何帮助! (此外,您认为我可以改进的有关我的实施的任何内容都将被亲切地接收(

好吧,每个人都已经解释过了,所以它应该像这样简单地将前向声明添加到.h文件的末尾:

#include <iostream>
class String
{
public:
String(const char * s);
String(const String &o);
int     size() const;
char    at(int i) const;
String  &operator+=(const String &o);
private:
char *  s;
int     n;
//needs to be a friend function defined OUTSIDE of the class as when using
//ostream << String you do not have access to the ostream so they can't be 
//member operators
friend std::ostream & operator<<(std::ostream &os, const String &o);
};
//forward declaration
String operator+(String lhs, const String &rhs);

前向声明只是告诉编译器查找具有该签名的函数。当它在当前.cpp文件中找不到它时,它会查找其他.cpp文件。我希望这有帮助!