operator new[] 연산자를 재정의하는데 오류가 납니다.
글쓴이: dltkddyd / 작성시간: 목, 2013/12/26 - 12:38오후
아래의 코드를 컴파일 하면 주석문에 나온 것과 같은 오류 문구가 출력됩니다.
#include <iostream>
using namespace std;
#include <new>
template<typename CARGT>
class D2 {
public:
CARGT** pt2;//error:invalid use of member 'D2<CARGT>::pt2' in static member function
void* operator new[](std::size_t size) throw(std::bad_alloc) {
pt2=new CARGT[size]*;//error: from this location
cout<<"nnnnn"<<endl;
}
};
int main() {
D2<int>* obj2;
obj2=new D2<int>[5];
//delete[] obj2;
return 0;
}operator new[]가 static이라고 나오는데 어떻게 해야 오류를 바로 잡을 수 있을까요?
Forums:


멤버 변수를 초기화하는건 new 연산자의 역할이
멤버 변수를 초기화하는건 new 연산자의 역할이 아니라 생성자의 역할입니다.
그래서 다시 만들어봤는데요.
원래의 의도는 그것이 아니었기 때문에 다시 ReD2로 만들어봤습니다. 내부의 일차포인터를 관리하는 클래시입니다.
template<typename CARGT> class ReD2 { public: CARGT* pt; const static unsigned int length; ReD2() {} ReD2(const ReD2<CARGT>& arg) {} ReD2(int num) { cout<<"ReD2(int num)"<<endl; //length=num; } void* operator new[](std::size_t size) throw(std::bad_alloc) { cout<<"operator new[]"<<size/4<<endl;//test ReD2<CARGT>* p=(ReD2<CARGT>*)malloc(size); if(!p) { bad_alloc ba; throw ba; } //length=_length/sizeof(ReD2<SARGT>); //cout<<"length is "<<length<<endl;//test return p; } void operator delete[](void* ptr) throw() { ReD2<CARGT>* tmp=(ReD2<CARGT>*)ptr; cout<<"operator delete[] "<<endl;//test cout<<tmp[0].pt[2]<<endl;//test free(tmp); //cout<<tmp[0].pt[2]<<endl;//test } }; int main() { ReD2<int>* obj3=new ReD2<int>[3]; }void* operator new[](std::size_t size) throw(std::bad_alloc)
라는 함수에서 정적변수인 length에 size/4 의 값을 설정하려 하는데 링크 오류가 발생합니다. 개수를 멤버변수 length로 넣을 수 있는 방법이 없을까요?
본인 맞습니다.
인증샷
우헤헤헤... 로 대신합니다.
SARGT는 뭔가요?
최소한 컴파일은 되게끔 소스를 올려 주셔야...
template<typename CARGT> class ReD2 { static size_t length; // const는 빼야죠. const 값을 바꾸려고 하면 안됩니다. // ... length=size/sizeof(ReD2<CARGT>); // ... }; template<typename CARGT> size_t ReD2<CARGT>::length = 0; // static 변수의 초기화는 이렇게 하면 됩니다.www.gilgil.net
댓글 달기