【发布时间】:2015-09-02 08:53:53
【问题描述】:
我正在用 c++ 编写自己的字符串类 StringEx(别担心,只是为了练习),但我无法通过为其分配字符串来创建我的类的实例:
StringEx string1 = StringEx("test"); // works fine
StringEx string2 = "test"; // doesn't work
string string3 = "test";
string1 = string3; // also works fine
我重载了赋值运算符,以便它可以处理std::string,但我必须先创建一个StringEx 的对象。
如何通过分配字符串来创建StringEx 的新对象?是否有可能让 c++ 处理每个 "string" 作为我的 StringEx 类的对象?
这是我的StringEx.h 现在可以使用
#ifndef STRINGEX_H
#define STRINGEX_H
#include <iostream>
#include <string>
#include <vector>
using namespace std; //simplyfying for now
class StringEx
{
private:
vector<char> text;
public:
StringEx();
StringEx(string);
StringEx(const char*); // had to add this
StringEx(vector<char>);
int size() const;
int length() const;
char at(int) const;
void append(const string&);
void append(const StringEx&);
void append(const char*); // had to add this
StringEx operator+(const string&);
StringEx operator+(const StringEx&);
StringEx operator+(const char*); // had to add this too
StringEx operator=(const string&);
StringEx operator=(const StringEx&);
StringEx operator=(const char*); // had to add this too
StringEx operator+=(const string&);
StringEx operator+=(const StringEx&);
StringEx operator+=(const char*); // had to add this too
friend ostream& operator<<(ostream&, const StringEx&);
};
#endif // STRINGEX_H
【问题讨论】:
-
这称为初始化(更准确地说,复制初始化),而不是赋值。赋值是在对象之前已经构造的时候(就像在你的上一个例子中一样)。
-
奇怪的是:这段代码在 VS2015 上编译得很好
-
你已经得到了一些答案,但你真的应该展示你的类的构造函数、复制构造函数和复制赋值的声明。
-
@SimonKraemer MSVC 从来都不是标准合规的典范。
-
@LPrulzcrossover 您的编辑显示了导致错误的
StringEx.h,还是现在有效的StringEx.h?请编辑您的问题并解释您所展示的内容。