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

我的头文件是:

#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

我的课是:
#include "Anagrams.h"
#include <string>
using namespace std;

Anagrams::Anagrams(string &s){
    word = s;
}

bool Anagrams::areTwoWordsAnagrams(string word1, string word2){
    int sizeOfWord1 = word1.size();
    int sizeOfWord2 = word2.size();

    int array1[26];
    int array2[26];

    for (int i = 0; i < 26; i++){ //Initialize both arrays
        array1[i] = 0;
        array2[i] = 0;
    }


    decomposeWordIntoLetters(word1,array1,sizeOfWord1);
    decomposeWordIntoLetters(word2,array2,sizeOfWord2);

    return true;
}

string Anagrams::getWord() const{
    return word;
}

void Anagrams::setWord(string &s){
    word = s;
}

void decomposeWordIntoLetters(string word, int array[], int size){
    for (int i = 0; i < size; i++){
        char letter = word[i];
        array['z' - letter]++;
    }
}

请注意,头文件中未定义decomposeWordIntoLetters函数。如果我将代码两次复制并粘贴到Anagrams::areTwoAnagrams(字符串word1,字符串word2)中,则该程序将运行。否则,我得到以下错误:
Anagrams.cpp: In static member function ‘static bool Anagrams::areTwoWordsAnagrams(std::string, std::string)’:
Anagrams.cpp:22: error: ‘decomposeWordIntoLetters’ was not declared in this scope

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

最佳答案

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

要声明一个函数,请提供其原型(prototype),如下所示:

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

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

当您定义这样的函数时,您可能不仅要对 header 隐藏它们,还要对链接到库的其他模块隐藏它们。为此,声明函数static:
static void decomposeWordIntoLetters(string word, int array[], int size);

请注意,当您对独立函数执行此操作时,static的含义完全不同:该函数不会像类作用域static函数一样成为类函数;相反,它变成一种功能,其可见性仅限于翻译单位(即定义了单个cpp文件)。

09-30 14:02
查看更多