参照とポインタ
Posted: 2009年5月19日(火) 16:38
引数の定義の仕方で良く分からない仕様だったので質問させてください
参照で関数funcを定義した場合,
_vec.retest()
と定義出来ますが,
ポインタで定義した場合,
_vec.retest()
_vec->retest()
2パターンで書いてもエラーが出ました.
'->'のパターン
$ g++ -o test test.cpp
test.cpp: In function ‘void func(std::vector<TEST, std::allocator<TEST> >*)’:
test.cpp:33: error: base operand of ‘->’ has non-pointer type ‘std::vector<TEST, std::allocator<TEST> >’
'.'のパターン
$ g++ -o test test.cpp
test.cpp: In function ‘void func(std::vector<TEST, std::allocator<TEST> >*)’:
test.cpp:33: error: ‘class std::vector<TEST, std::allocator<TEST> >’ has no member named ‘retest’
呼び方に大きな違いがあるとは思うのですが,参照とポインタの違いを良く分かっていないのが現状です.
詳しい方,よろしくお願いします.
*参照*
*ポインタ*
参照で関数funcを定義した場合,
_vec.retest()
と定義出来ますが,
ポインタで定義した場合,
_vec.retest()
_vec->retest()
2パターンで書いてもエラーが出ました.
'->'のパターン
$ g++ -o test test.cpp
test.cpp: In function ‘void func(std::vector<TEST, std::allocator<TEST> >*)’:
test.cpp:33: error: base operand of ‘->’ has non-pointer type ‘std::vector<TEST, std::allocator<TEST> >’
'.'のパターン
$ g++ -o test test.cpp
test.cpp: In function ‘void func(std::vector<TEST, std::allocator<TEST> >*)’:
test.cpp:33: error: ‘class std::vector<TEST, std::allocator<TEST> >’ has no member named ‘retest’
呼び方に大きな違いがあるとは思うのですが,参照とポインタの違いを良く分かっていないのが現状です.
詳しい方,よろしくお願いします.
*参照*
#include<iostream> #include<vector> class TEST { private: int test; public: TEST(int i) : test(i * 10) {} int retest() {return test;} }; void func(std::vector<TEST>&); int main(void) { std::vector<TEST> vec; for(int i = 0; i < 10; i++) vec.push_back(TEST(i)); std::cout << "main" << std::endl; for(int i = 0; i < 10; i++) std::cout << vec.retest() << std::endl; func(vec); return 0; } void func(std::vector<TEST>& _vec) { for(int i = 0; i < 10; i++) std::cout << _vec.retest() << std::endl; }
*ポインタ*
#include<iostream> #include<vector> class TEST { private: int test; public: TEST(int i) : test(i * 10) {} int retest() {return test;} }; void func(std::vector<TEST>*); int main(void) { std::vector<TEST> vec; for(int i = 0; i < 10; i++) vec.push_back(TEST(i)); std::cout << "main" << std::endl; for(int i = 0; i < 10; i++) std::cout << vec.retest() << std::endl; func(&vec); return 0; } void func(std::vector<TEST>* _vec) { for(int i = 0; i < 10; i++) std::cout << _vec.retest() << std::endl; }