好的,非常简单的String
类,它包含常量字符串(即一旦初始化就不能更改),实现了复制 ctor 和连接功能conc
。正是这个函数给我带来了麻烦,因为我真的无法弄清楚为什么我创建的局部变量没有作为返回值正常传递。
代码:
class String
{
public:
String(char*);
String(const String& other);
~String();
friend String conc(const String&, const String&);
friend std::ostream& operator<<(std::ostream&, const String&);
private:
const char* const str;
};
String::String(char* aStr) : str(aStr) {}
String::String(const String& other) : str(other.str) {}
std::ostream& operator<<(std::ostream& out, const String& s)
{
out<<s.str<<"\n";
return out;
}
String::~String()
{
delete str;
}
String conc(const String& s1, const String& s2)
{
int n = strlen(s1.str) + strlen(s2.str);
int i, j;
char* newS = new char[n+1];
for(i = 0; i < strlen(s1.str); ++i)
{
newS[i] = s1.str[i];
}
for(j = 0; j < strlen(s2.str); ++j)
{
newS[i+j] = s2.str[j];
}
newS[i+j] = '\0'; //newS is made correctly
String tmp(newS); // the tmp object is made correctly
return tmp; // here tmp becomes something else --- Why??
}
int main()
{
String s1("first");
String s2("SECOND");
String s3 = conc(s1, s2); //here the copy ctor should be called, right?
std::cout<<s3;
_getch();
}
正如您在评论中看到的那样,问题出在conc
最后的函数中。我已经让函数返回 a String
,而不是String&
故意的,因为它返回的值不应该是左值......
请解释和帮助,谢谢!:)