std::string 在参数中构造
std::string Constructed in Arguments
我遇到了一个非常棘手的C++编译器错误。
当我构造一个字符串以用作参数时,它在调用常规方法时有效。 例如 printThisString(string(charPtr));
如果构造函数的参数是char*
,则在构造对象时它不起作用。例如,如果参数是文字,MyObject a(string(argv[0]));
它仍然有效。例如,MyObject b(string("hi"));
#include <iostream>
#include <string>
using namespace std;
void printString(string toPrint) {
cout << toPrint << endl;
}
class MyObject {
int blah;
public:
void aMethod() {}
MyObject (string myStr) {
cout << myStr << endl;
}
};
int main(int argc, char ** argv) {
string s1(argv[0]);
char * s2 = "C-style string"; // I realize this is bad style
printString(string("Hello world!")); // All of these work
printString(s1);
printString(string(s2));
printString(string(argv[0]));
MyObject mo1 (string("Hello world!")); // Valid
MyObject mo2 (s1); // Valid
MyObject mo3 (string(s2)); // Does not print
MyObject mo4 (string(argv[0])); // Does not print
mo1.aMethod();
mo2.aMethod();
mo3.aMethod(); // Error
mo4.aMethod(); // Error
return 0;
}
对于 mo3 和 mo4,可以创建对象,但不能使用任何方法。它们属于错误的类型。编译器似乎认为它们是函数...
test.cpp: In function 'int main(int, char**)':
test.cpp:22:13: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
test.cpp:36:5: error: request for member 'aMethod' in 'mo3', which is of non-class type 'MyObject(std::string) {aka MyObject(std::basic_string<char>)}'
test.cpp:37:5: error: request for member 'aMethod' in 'mo4', which is of non-class type 'MyObject(std::string*) {aka MyObject(std::basic_string<char>*)}'
这只是最令人烦恼的解析的变体:mo3
和mo4
是函数声明而不是对象定义。您可以使用以下方法解决问题
MyObject mo3 {string(s2)};
MyObject mo4 {string(argv[0])};
或
MyObject mo3 ((string(s2)));
MyObject mo4 ((string(argv[0])));
或
MyObject mo3 = MyObject(string(s2));
MyObject mo4 = MyObject(string(argv[0]));
或。。。
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 确切地说,如何解释 std::getline(stream, string) 函数在C++中填充的字符串
- C++:考虑C++ std::string 中双引号 (") 的字面含义,而不使用反斜杠 (\)
- 'int main(int, int, std::__cxx11::string, std::__cxx11::string)'只需要零或两个参数 [-Wmain]
- C++ 在列表和列表之间选择返回类型<<string>std::p air<string,string>>
- std::string, std::wstring and UTF8
- uan inplace replacement of std::string/std::wstring?
- #define Glib::string std:wstring
- 从 std::string & std::wstring 中获取 char 整数值
- BSTR转换为std::string(std::wstring),反之亦然