C++11 について根本的な誤解があるに違いありません。私の教授は、参照またはポインター以外では、非プリミティブ型を関数に渡すことはできないと言いました。ただし、次のコードは問題なく動作します
#include <iostream>
using namespace std;
class MyClass
{
public:
int field1;
};
void print_string(string s) {
cout << s << endl;
}
void print_myclass(MyClass c) {
cout << c.field1 << endl;
}
int main(int argc, char *argv[])
{
string mystr("this is my string");
print_string(mystr); // works
MyClass m;
m.field1=9;
print_myclass(m);
return 0;
}
プログラムを実行すると、次の出力が得られます
this is my string
9
RUN SUCCESSFUL (total time: 67ms)
Win7 で MinGW/g++ を使用しています
なぜそれが機能するのですか?非プリミティブ型は値渡しできないと思っていた?!