OOP - 正常类到文件分隔的类

时间:2016-11-20 01:25:01

标签: c++ file oop

我做了一个很好的课程。 没有必要尝试理解我可怕的代码。

我要问的是:如何将此类编入class.cpp和头文件?

所以这里的这个是工作版本:

class Dictionary {

public:

    Dictionary() {
        cout << "Welcome to the constructor" << endl;
    }

void insertWordFun(string word, string lookup, vector<string>& v1, vector<string>& v2) {
    cout << "Accessing add funciton ~" << endl;
    int wordInVector = 0;

    cout << "\nYou chose option #1." << endl;
    cout << "Please insert word: ";
    getline(cin, word);

    for (int i = 0; i < v1.size(); i++) {
        if (v1[i] == word) {
            cout << "Word already exists." << endl;
            wordInVector = 1;
            break;
        }
    }
    if (wordInVector == 0) {
        v1.push_back(word);
        cout << "Describe your word: ";
        getline(cin, lookup);
        v2.push_back(lookup);
    }
}
};

下面的代码就是当我试图将这个类分成文件而失败时:

.h文件:

#pragma once
class Dictionary
{
public:
    Dictionary();
    void insertWordFun(string word, string lookup, vector<string>& v1, vector<string>& v2);
};

Dictionary.cpp(类文件):

#include "Dictionary.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;

Dictionary::Dictionary(){
    cout << "Welcome to the constructor" << endl;
};

void Dictionary::insertWordFun(string word, string lookup, vector<string>& v1, vector<string>& v2) {
    cout << "Accessing add funciton ~" << endl;
    int wordInVector = 0;

    cout << "\nYou chose option #1." << endl;
    cout << "Please insert word: ";
    getline(cin, word);

    for (int i = 0; i < v1.size(); i++) {
        if (v1[i] == word) {
            cout << "Word already exists." << endl;
            wordInVector = 1;
            break;
        }
    }
    if (wordInVector == 0) {
        v1.push_back(word);
        cout << "Describe your word: ";
        getline(cin, lookup);
        v2.push_back(lookup);
    }
};

Source.cpp(主文件):

#include "Dictionary.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;
int main()
{
    vector<string> v1;
    vector<string> v2;
    string word;
    string lookup;
    string choice;

    Dictionary obj;

    while (true) {
        getline(cin, choice);
        if (choice == "1") {
            obj.insertWordFun(word, lookup, v1, v2);

1 个答案:

答案 0 :(得分:0)

您需要#include标头文件中使用的组件的标头。例如,#include <vector>需要位于您的头文件中。

您需要在标头中的相应类型前面明确指定std::,例如vectorstring。您不应在头文件中使用using namespace std;,但可以在.cpp文件中使用它。