Domanda

I've run into a very tricky C++ compiler error.

When I construct a string to use as an argument, it works when calling a regular method. E.g. printThisString(string(charPtr));

It does not work when constructing an object, if the argument to the constructor is a char*. For example, MyObject a(string(argv[0])); It still does work if the argument is a literal. For example, 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;
}

For mo3 and mo4, the objects can be created, but no methods can be used. They are of the wrong typ. It appears that the compiler thinks they are functions...

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>*)}'
È stato utile?

Soluzione

This is just a variation of the most vexing parse: mo3 and mo4 are function declarations rather than object definitions. You can fix the problem using

MyObject mo3 {string(s2)};
MyObject mo4 {string(argv[0])};

or

MyObject mo3 ((string(s2)));
MyObject mo4 ((string(argv[0])));

or

MyObject mo3 = MyObject(string(s2));
MyObject mo4 = MyObject(string(argv[0]));

or ...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top