매우 까다로운 C++ 컴파일러 오류가 발생했습니다. 일반 메서드를 호출 할 때 std :: string Constructed in Arguments
내가 인수로 사용할 수있는 문자열을 만들
, 그것은 작동합니다. 예 :printThisString(string(charPtr));
생성자에 대한 인수가 char*
인 경우 객체를 생성 할 때 작동하지 않습니다. 예 : MyObject a(string(argv[0]));
인수가 리터럴 인 경우에도 작동합니다. 예를 들어, MO3 MyObject b(string("hi"));
및 MO4 들어
#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;
}
, 객체가 생성 될 수 있지만, 어떤 방법을 사용할 수 없다. 그들은 틀린 타입이다.
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>*)}'
에 오신 것을 환영합니다 C에 ++, 가장 골치 아픈 구문 분석의 가정을 사용하여 문제를 해결할 수 있습니다. – chris
C++ 11을 지원하는 컴파일러를 사용 하시겠습니까? – goji
이 때문에'Type variable = ...;'선언문을 선호해야합니다. 할당이 생략되어 '변수 유형 (...);과 모호성을 뺀 것과 동일한 결과가 나타납니다. (생성자가'explicit'이 아니라고 가정하면,'Type variable = Type (...); '이라고 써야하지만 같은 코드를 다시 생성해야합니다.) – syam