Member function definition outside of class

2019-02-25 15:54发布

Is it possible to define function or method outside class declaration? Such as:

class A 
{
    int foo;
    A (): foo (10) {}
}

int A::bar () 
{
    return foo;
}        

3条回答
对你真心纯属浪费
2楼-- · 2019-02-25 16:46

It is possible to define but not declare a method outside of the class, similar to how you can prototype functions in C then define them later, ie:

class A 
{
    int foo;
    A (): foo (10) {}
    int bar();
}

// inline only used if function is defined in header
inline int A::bar () { return foo; }   
查看更多
迷人小祖宗
3楼-- · 2019-02-25 16:47

You can define a method outside of your class

// A.h
#pragma once
class A 
{
public:
    A (): foo (10) {}
    int bar();
private:
    int foo;
};

// A.cpp
int A::bar () 
{
    return foo;
}

But you cannot declare a method outside of your class. The declaration must at least be within the class, even if the definition comes later. This is a common way to split up the declarations in *.h files and implementations in *.cpp files.

查看更多
Explosion°爆炸
4楼-- · 2019-02-25 16:59

Yes, but you have to declare it first in the class, then you can define it elsewhere (typically the source file):

// Header file
class A 
{
    int foo = 10;
    int bar(); // Declaration of bar
};

// Source file
int A::bar() // Definition of bar 
{
    return foo;
} 
查看更多
登录 后发表回答