내 벡터를 반복하고 벡터에 저장된 항목의 주소를 얻으려고했습니다. 다른 유형의 반복자 (아래 참조)에서 작동하지만 이렇게하려고하면 for(auto it :my_vec)
오류가 발생합니다.error: no match for 'operator*' (operand type is 'my_class')
#include <iostream>
#include <vector>
class my_class{
int x;
public:
my_class(int x_):x(x_){}
};
std::vector<my_class> my_vec;
void fill_vec(size_t size){
for(int i = 0; i < size; i++){
my_vec.push_back(my_class(i));
}
}
int main(){
size_t size = 10;
fill_vec(size);
for(auto it :my_vec){
std::cout << &it << std::endl;
std::cout << &(*it) << std::endl;
}
std::cout << "-----------" << std::endl;
for(auto it = my_vec.begin(); it != my_vec.end(); it++){
std::cout << &(*it) << std::endl;
}
std::cout << "-----------" << std::endl;
for(size_t i = 0; i < my_vec.size(); i++){
std::cout << &my_vec[i] << std::endl;
}
return 0;
}
for 루프를 기반으로 범위 내의 객체 주소를 얻는 방법은 무엇입니까?
다른 곳에서 객체의 주소를 얻는 것과 같은 방법 : addressof 연산자 ( operator&
)를 사용합니다 .
다른 유형의 반복자 (아래 참조)에서 작동하지만 이렇게하려고하면
for(auto it :my_vec)
오류가 발생합니다.error: no match for 'operator*' (operand type is 'my_class')
범위 기반 for 루프는 반복자를 제공하지 않습니다. 그것은 당신에게 물건을줍니다. 이 경우를 사용 했으므로 벡터에있는 객체의 복사 auto
본인 my_class
인스턴스 ( value_type
컨테이너의 것이기 때문에)를 제공합니다 . (비 참조 연산자)에 my_class
대한 오버로드가 없으므로 operator*
시도한 줄 (포함 *it
)이 작동하지 않았고 컴파일러가 문제를 설명합니다.
따라서 std::cout << &it << std::endl;
정확하지만 벡터의 객체가 아닌 사본의 주소를 제공합니다. 벡터에있는 객체의 주소를 원할 것이므로 대신 auto&
또는 my_class&
참조를 가져와야합니다. addressof 연산자에 대한 피연산자로 참조를 사용하면 참조 된 객체의 주소를 얻습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다