gpt4 book ai didi

c++ - std::string 在参数中构造

转载 作者:行者123 更新时间:2023-11-28 07:22:58 25 4
gpt4 key购买 nike

我遇到了一个非常棘手的 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>*)}'

最佳答案

这只是 most vexing parse 的变体: mo3mo4 是函数声明而不是对象定义。您可以使用

解决问题
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]));

或者...

关于c++ - std::string 在参数中构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19170713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com