如何在C+中在类中而不是在头文件中添加函数+;? 我目前正在用C++编写写作课和头文件。我有一个问题:假设在我的头文件中有一个客户端可以使用的公共函数,我知道如何在相应的类中实现它。但是,假设这个函数分为几个步骤,这些步骤可以作为独立函数编写,我不希望用户看到(保护知识产权)。通常,对于头文件中定义的每个函数,我将在.cpp文件中写入myClassName::myFunctionName(参数1..)。是否有办法仅在.cpp文件中定义和使用函数?例如,我编写了一个程序来查看两个单词是否是字谜(字母相同)

如何在C+中在类中而不是在头文件中添加函数+;? 我目前正在用C++编写写作课和头文件。我有一个问题:假设在我的头文件中有一个客户端可以使用的公共函数,我知道如何在相应的类中实现它。但是,假设这个函数分为几个步骤,这些步骤可以作为独立函数编写,我不希望用户看到(保护知识产权)。通常,对于头文件中定义的每个函数,我将在.cpp文件中写入myClassName::myFunctionName(参数1..)。是否有办法仅在.cpp文件中定义和使用函数?例如,我编写了一个程序来查看两个单词是否是字谜(字母相同),c++,function,scope,C++,Function,Scope,我的头文件是: #ifndef _Anagrams_h #define _Anagrams_h #include <string> using namespace std; class Anagrams{ public: Anagrams(string &s); static bool areTwoWordsAnagrams(string s1, string s2) ; string getWord()const;

我的头文件是:

#ifndef _Anagrams_h
#define _Anagrams_h
#include <string>
using namespace std;

class Anagrams{
    public:
        Anagrams(string &s);
        static bool areTwoWordsAnagrams(string s1, string s2) ; 
        string getWord()const; 
        void setWord(string &s);

    private:
        string word;

};
#endif

任何帮助都将不胜感激。谢谢。

您的cpp文件中肯定可以包含非成员函数。但是,在声明或定义这些函数之前,不能使用它们

要声明函数,请提供其原型,如下所示:

void decomposeWordIntoLetters(string word, int array[], int size);

将此行放在调用
decomposeOrdintoLetters
的成员函数上方。这将解决您看到的编译问题

当您定义这样的函数时,您可能希望不仅从标题中隐藏它们,而且从链接到库的其他模块中隐藏它们。为此,请声明函数
static

static void decomposeWordIntoLetters(string word, int array[], int size);

请注意,当您对独立函数执行此操作时,
静态
的含义完全不同:函数不会成为类作用域
静态
函数的类函数;相反,它成为一个可视性仅限于翻译单元的函数(即定义它的单个cpp文件)。

没有办法使类成员函数不出现在类声明中,因此,如果类的声明对使用它的代码可见,则所有成员函数都可见

有一些方法可以隐藏整个类的实现,比如“指向实现的指针”模式:公开一个类,它只是一个接口。它持有一个指向某个不透明对象(其完整类型声明不向用户公开)的指针,所有公共函数都只是调用该对象上函数的包装器

class hidden_from_user;

class exposed_to_user {
private:
  hidden_from_user *impl;
public:
  // constructors, destructors, and so on.
  void frob(int howmuch);   
};
在CPP文件中:

// full declaration of hidden_from_user is available here
#include "hidden_from_user.h"  // private header, not shipped as part of API
#include "exposed_to_user.h"

// ...

void exposed_to_user::frob(int howmuch)
{
   impl->frob(howmuch);
}

您可以自由地从用户更改
隐藏的put
decompositeOrdintoLetters
over
Anagrams::AreTwordSanAgrams
,应该可以吗?
decompositeOrdintoLetters
需要声明才能使用。将转发声明添加到源文件的开头。您可能希望更改include guard命名约定。保留以下划线开头,后跟大写字母的名称。看见
class hidden_from_user;

class exposed_to_user {
private:
  hidden_from_user *impl;
public:
  // constructors, destructors, and so on.
  void frob(int howmuch);   
};
// full declaration of hidden_from_user is available here
#include "hidden_from_user.h"  // private header, not shipped as part of API
#include "exposed_to_user.h"

// ...

void exposed_to_user::frob(int howmuch)
{
   impl->frob(howmuch);
}