C++のwhich is of non-class typeにハマる
c++のstringクラスと文字列ポインタの関係について調べていたわけですよ.
#include <iostream> using namespace std; class Color { string color; public: Color(string a) { cout<<"Color"<<endl; color = a; } void echo() { cout<<color<<endl; } ~Color() { } }; int main(int argc, char *argv[]){ Color c(string(argv[1])); c.echo(); return(0); }
こんなプログラムで,引数で与えた文字列が表示されるのを期待しました.ところが
$ c++ test.cc test.cc: In function 'int main(int, char**)': test.cc:22: error: request for member 'echo' in 'c', which is of non-class type 'Color ()(std::string*)'
C型文字列をstringに変換して渡したつもりが,stringのポインタと解釈されているようです.
そうか,newが省略されているような感じに解釈されるのか.こんな感じにプログラムを変えても,
int main(int argc, char *argv[]){ Color c(new string(argv[1])); c.echo(); return(0); }
似たようなエラーが出ます.
$ c++ test.cc test.cc: In function 'int main(int, char**)': test.cc:21: error: no matching function for call to 'Color::Color(std::string*)' test.cc:7: note: candidates are: Color::Color(std::string) test.cc:4: note: Color::Color(const Color&)
ということは,受け取り側でポインタとして受け取るか,stringはcharのポインタで初期化できるからstring変換をやめるかですね.
int main(int argc, char *argv[]){ Color c(argv[1]); c.echo(); return(0); }
変換をやめてみた.
$ c++ test.cc $ ./a.out red Color red
OK.