저는 C++의 초보자입니다.하지만 다음과 같은 것을 발견했습니다.해당 함수를 다른 번역 단위에서 링크 할 경우 클래스의 멤버 함수를 정의 할 수없는 이유는 무엇입니까?
나는이 파일이있는 경우 :
myclass.hpp :
class myclass {
public:
myclass();
void barf();
};
mymain.cpp :
#include "myclass.hpp"
int main() {
myclass m;
m.barf();
return 0;
}
내가 MyClass에의이 구현 사용
myclassA합니다. cpp :
#include <iostream>
using namespace std;
class myclass { // or include myclass.hpp, it both works fine
public:
myclass();
void barf();
};
myclass::myclass() { } //empty
void myclass::barf() {
cout << "barfing\n";
}
모든 것이 정상입니다.
myclassB.cpp :
#include <iostream>
using namespace std;
class myclass {
public:
myclass() { }
void barf() {
cout << "barfing\n";
}
};
내가 오류 나는 멤버가 클래스 정의 내에서 정의 된 것을 제외하고 완전히 동일 MyClass의의 구현을 사용하는 경우에, 나는 연결 오류가 발생합니다 :
$ g++ myclassB.cpp mymain.cpp
/tmp/cc4DTnDl.o: In function `main':
mymain.cpp:(.text+0xd): undefined reference to `myclass::myclass()'
mymain.cpp:(.text+0x16): undefined reference to `myclass::barf()'
collect2: ld returned 1 exit status
분명히 myclassB.cpp에서 빌드 된 개체 파일은 멤버 함수를 내 보내지 않습니다. 이러한 구현이 모두 동일한 방식으로 작동하지 않는 이유는 무엇입니까? C++에서 클래스 정의 안에있는 멤버 정의가 전역 적으로 보이지는 않지만, 클래스 외부에 정의되어 있다면 멤버 규칙이란 규칙이 있습니까?
나에게 그의 질문은 실제로 한 번만 클래스를 정의하는 것처럼 들렸지 만 그 정의는 소스 파일 내에서 두 번째 클래스 선언 안에있었습니다. – smerlin
그는 myclass.hpp를 mymain.cpp에 포함시킨 다음 g ++ myclassB.cpp mymain.cpp을 사용하여 컴파일하려고했습니다. – Jagannath