C ++将当前对象传递给自由函数

时间:2018-04-07 05:27:15

标签: c++

这可能是一个简单的问题,但我无法将'当前对象'传递给一个将其作为参数的自由函数。

这是一个简单的例子,说明了我的问题。

我有一个Cat类,以及一个基于Cat对象创建模因的外部函数“createCatMeme”。但是如果我想要一个Cat对象对自己的模因做出“反应”,并且反应是一种Cat方法,我该如何将当前的Cat传递给“createCatMeme”?

class Cat
{
    std::string name;

    Cat() {...}

    inline react(Meme meme) {...}

    inline reactToOwnMeme()
    {
        Meme meme = createCatMeme(/* How do I pass in the 'current' Cat object? */);
        react(meme);
    }

};

Meme createCatMeme(const Cat& c);

1 个答案:

答案 0 :(得分:5)

  

如何将当前的Cat传递给" createCatMeme"?

使用*this

inline reactToOwnMeme()
{
    Meme meme = createCatMeme(*this);
    react(meme);
}

但是,要做到这一点,必须在函数定义之前声明createCatMeme

我注意到reactToOwnMeme dos没有返回类型。

选项1

在类定义之前声明函数。

// Forward declare the class.
class Cat;

// Declare the function
Meme createCatMeme(const Cat& c);

// Define the class.
class Cat
{
   ...

    inline void reactToOwnMeme() // Assuming void as return type.
    {
        Meme meme = createCatMeme(*this);
        react(meme);
    }
};

选项2

在类定义之后声明函数。为此,必须在类定义之外定义成员函数。

// Define the class.
class Cat
{
   ...

    // Declare the member function
    void reactToOwnMeme();
};

// Declare the function
Meme createCatMeme(const Cat& c);

// Define the member function
void Cat::reactToOwnMeme();
{
    Meme meme = createCatMeme(*this);
    react(meme);
}