通过重载=运算符从std::String创建String对象
Create String object from std::string by overloading = operator
我尝试了几个选项,但我的编译器没有发现运算符重载或其他问题。我使用XCode 4.5.2和默认的Apple LLVM编译器4.1。
我得到的错误是:Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]'
在这些线路上:
CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";
我的.h代码:
CCString& operator= (const std::string& str);
// CCString& operator= (const char* str); // this doesn't work either
const CCString& operator = (const char *);
我的.cpp代码(即使这是无关的(:
CCString& CCString::operator= (const std::string& str)
{
m_sString = CCString::create(str)->m_sString;
return *this;
}
const CCString& CCString :: operator = (const char* str)
{
m_sString = CCString::create(str)->m_sString;
return *this;
}
非常感谢您的帮助,谢谢!
错误消息Assigning to 'cocos2d::CCString *' from incompatible type 'const char [5]'
表明您正在为指向cocos2d::CCString
的指针分配一个char数组。
这应该有效:
char bar[] = "ABCD";
cocos2d::CCString foo;
foo = bar;
CCString *s_piece__locks = "TEST";
cocos2d::CCString *s_piece__locks2 = "TEST";
这到底是怎么回事?声明指针不会生成除指针本身之外的任何对象。因此,基本上,为了"工作",需要已经有另一个CCString
对象,它恰好代表字符串"TEST"。但即使给出了这个,C++怎么知道该指向哪一个呢?它需要在某种例如散列映射中查找"TEST"
。
这些都没有任何意义。将代码更改为任一
直接使用堆栈上的对象:
cocos2d::CCString s_piece; s_piece = "TEST";
将新内容分配给位于其他位置的对象。对此,您通常会使用参考,例如
void assign_test_to(cocos2d::CCString& target) { target = "TEST"; }
也可以使用指针
void assign_test_to_ptr(cocos2d::CCString* target) { *target = "TEST"; }
但除非你有特定的理由,否则不要这样做。
原则上,还有另一种可能性:
cocos2d::CCString* s_piece_locks = new CCString;
*s_piece_locks = "TEST";
但您需要避免这种情况,因为它很容易导致内存泄漏。可以
std::unique_ptr<cocos2d::CCString> s_piece_locks = new CCString;
*s_piece_locks = "TEST";
相关文章:
- 在共享缓冲区内存中创建 ::std::string 对象
- 创建 std::string 的二维数组的最佳做法
- C++从 std::string 创建 CString 失败
- std::string::reserve没有被允许创建具有精确容量的std::string
- 通过预处理器创建 std::p air<std::string,some_enum>
- 使用std :: to_string()创建std :: String时的segfault
- 将C 数组写成文件,避免创建std :: String
- 如何从JSON String创建工厂方法
- C 使用默认限制的迭代器创建一个空的std :: String
- 如何使用矢量数据使用 rapidjson 库创建 json 文件<string>?
- 从 C++ std::string& 获取 unichar * 以在 Objective-C++ 中创建非空 NSString
- 动态创建 std::string 时的两个"新"调用
- 通过读取文件创建映射<字符串,矢量>时如何管理内存<string>
- "std::string + char"表达式会创建另一个 std::string 吗?
- C++ STL:在创建 std::string 的 const 副本时将更改 c_str()
- 如果 std::string 从未被修改,它可以在创建后移动吗?
- 需要一个宏来从 std::ostringstream 和 << arg 列表创建 std::string
- 您将如何为 std::list<std::string> 创建一个类型映射,以在<String> List in C++ 中为 Java 在 SWIG 中创建?
- std::string创建一个值
- 通过重载=运算符从std::String创建String对象