code

클래스 내부 또는 외부의 함수 선언

codestyles 2020. 10. 8. 08:01
반응형

클래스 내부 또는 외부의 함수 선언


저는 C ++를 배우려는 JAVA 개발자이지만 표준 함수 선언에 대한 모범 사례가 무엇인지 실제로는 모릅니다.

수업에서 :

class Clazz
{
 public:
    void Fun1()
    {
        //do something
    }
}

또는 외부 :

class Clazz
{
public:
    void Fun1();
}

Clazz::Fun1(){
    // Do something
}

두 번째는 가독성이 떨어질 수 있다는 느낌이 듭니다.


C ++는 소프트웨어 개발을위한 객체 지향 패러다임을 지원한다는 점에서 객체 지향입니다.

그러나 Java와 달리 C ++는 클래스에서 함수 정의를 그룹화하도록 강요하지 않습니다. 함수를 선언하는 표준 C ++ 방식은 클래스없이 함수를 선언하는 것입니다.

대신 메서드 선언 / 정의에 대해 이야기하는 경우 표준 방법은 선언 만 포함 파일 (일반적으로 .hor .hpp)에 넣고 정의를 별도의 구현 파일 (일반적으로 .cppor .cxx) 에 넣는 것입니다 . 나는 이것이 실제로 다소 성 가시고 약간의 중복이 필요하다는 데 동의하지만 언어가 설계된 방식입니다.

빠른 실험과 단일 파일 프로젝트의 경우 모든 것이 작동하지만 더 큰 프로젝트의 경우 이러한 분리가 실제로 필요한 것입니다.

참고 : Java를 알고 있더라도 C ++는 완전히 다른 언어이며 실험으로 배울 수없는 언어입니다. 그 이유는 많은 비대칭과 비논리적 인 선택이있는 다소 복잡한 언어이기 때문이며, 가장 중요한 것은 실수를했을 때 Java에서 좋아하는 "런타임 오류 천사"가 없다는 것입니다.하지만 대신 " 정의되지 않은 동작 데몬 ".

C ++를 배우는 합리적인 유일한 방법은 읽는 것입니다 ... 아무리 똑똑하더라도위원회가 결정한 내용을 추측 할 수있는 방법이 없습니다 (정답이 비논리적이고 역사적 결과이기 때문에 실제로 똑똑하다는 것은 때때로 문제가되기도합니다. 세습 재산.)

좋은 책 한두 권을 골라 전체적으로 읽으십시오.


첫 번째는 멤버 함수를 인라인 함수 로 정의 하고 두 번째는 그렇지 않습니다. 이 경우 함수의 정의는 헤더 자체에 있습니다.

두 번째 구현에서는 함수 정의를 cpp 파일에 배치합니다.

둘 다 의미가 다르며 스타일의 문제가 아닙니다.


함수 정의는 클래스 밖에서 더 좋습니다. 이렇게하면 필요한 경우 코드를 안전하게 유지할 수 있습니다. 헤더 파일은 선언 만 제공해야합니다.

누군가가 당신의 코드를 사용하고 싶어한다고 가정하면, 당신은 그에게 당신의 클래스의 .h 파일과 .obj 파일 (컴파일 후에 얻은)을 줄 수 있습니다. 코드를 사용하기 위해 .cpp 파일이 필요하지 않습니다.

이렇게하면 구현이 다른 사람에게 표시되지 않습니다.


"Inside the class"(I) 메서드는 "outside the class"(O) 메서드와 동일합니다.

그러나 (I)는 클래스가 하나의 파일 (.cpp 파일 내부)에서만 사용되는 경우 사용할 수 있습니다. (O)는 헤더 파일에있을 때 사용됩니다. cpp 파일은 항상 컴파일됩니다. #include "header.h"를 사용하면 헤더 파일이 컴파일됩니다.

헤더 파일에서 (I)를 사용하면 #include "header.h"를 포함 할 때마다 (Fun1) 함수가 선언됩니다. 이로 인해 동일한 함수를 여러 번 선언 할 수 있습니다. 이것은 컴파일하기가 더 어렵고 오류가 발생할 수도 있습니다.

올바른 사용법의 예 :

파일 1 : "Clazz.h"

//This file sets up the class with a prototype body. 

class Clazz
{
public:
    void Fun1();//This is a Fun1 Prototype. 
};

File2 : "Clazz.cpp"

#include "Clazz.h" 
//this file gives Fun1() (prototyped in the header) a body once.

void Clazz::Fun1()
{
    //Do stuff...
}

File3 : "UseClazz.cpp"

#include "Clazz.h" 
//This file uses Fun1() but does not care where Fun1 was given a body. 

class MyClazz;
MyClazz.Fun1();//This does Fun1, as prototyped in the header.

File4 : "AlsoUseClazz.cpp"

#include "Clazz.h" 
//This file uses Fun1() but does not care where Fun1 was given a body. 

class MyClazz2;
MyClazz2.Fun1();//This does Fun1, as prototyped in the header. 

File5 : "DoNotUseClazzHeader.cpp"

//here we do not include Clazz.h. So this is another scope. 
class Clazz
{
public:
    void Fun1()
    {
         //Do something else...
    }
};

class MyClazz; //this is a totally different thing. 
MyClazz.Fun1(); //this does something else. 

Member functions can be defined within the class definition or separately using scope resolution operator, ::. Defining a member function within the class definition declares the function inline, even if you do not use the inline specifier. So either you can define Volume() function as below:

class Box
{
  public:

     double length;
     double breadth;    
     double height;     

     double getVolume(void)
     {
        return length * breadth * height;
     }
};

If you like you can define same function outside the class using scope resolution operator, :: as follows

double Box::getVolume(void)
{
   return length * breadth * height;
}

Here, only important point is that you would have to use class name just before :: operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows:

Box myBox;           

myBox.getVolume();  

(from: http://www.tutorialspoint.com/cplusplus/cpp_class_member_functions.htm) , both ways are legal.

I'm not an expert, but I think, if you put only one class definition in one file, then it does not really matter.

but if you apply something like inner class, or you have multiple class definition, the second one would be hard to read and maintained.


The first one must be put in the header file (where the declaration of the class resides). The second can be anywhere, either the header or, usually, a source file. In practice you can put small functions in the class declaration (which declares them implicitly inline, though it's the compiler that ultimately decides whether they will be inlined or not). However, most functions have a declaration in the header and the implementation in a cpp file, like in your second example. And no, I don't see any reason why this would be less readable. Not to mention you could actually split the implementation for a type across several cpp files.


A function that is defined inside a class is by default treated as an inline function. A simple reason why you should define your function outside:

A constructor of the class checks for virtual functions and initializes a virtual pointer to point to the proper VTABLE or the virtual method table, calls the base class constructor, and initializes variables of the current class, so it actually does some work.

The inline functions are used when functions are not so complicated and avoids the overhead of the function call. (The overhead includes a jump and branch on the hardware level.) And as described above, the constructor is not as simple to be considered as inline.

참고URL : https://stackoverflow.com/questions/9075931/function-declaration-inside-or-outside-the-class

반응형