visual 将类分为 cpp 和头文件 (C++)

visual Separating a class into cpp and header file (C++)

本文关键字:文件 C++ cpp visual      更新时间:2023-10-16

我是C++语言的新手。因此,我被分配将现有文件拆分为三个源代码:swap.h,swap.cpp和source3.cpp

现有文件:

#include <iostream>
void get_numbers (int&, int&);
void swap_values (int&, int&);
void show_results (int, int);
int main () {
   int first_num, second_num;
   get_numbers (first_num, second_num);
   swap_values (first_num, second_num);
   show_results (first_num, second_num);
   return 0;
}
void get_numbers (int& input1, int& input2) {
   using namespace std;
   cout << "Enter two integers: ";
   cin >> input1 >> input2;
}
void swap_values (int& variable1, int& variable2) {
   int temp;
   temp = variable1;
   variable1 = variable2;
   variable2 = temp;
}
void show_results (int output1, int output2) {
   using namespace std;
   cout << "In reverse order the numbers are: "
        << output1 << " " << output2 << endl;
}
  1. swap.h 包含函数原型

  2. swap.cpp 包含函数实现

  3. source3.cpp 包含主函数

对于交换.h:

#pragma once
#ifndef swap_h
#define swap_h
void get_numbers(int&, int&);
void swap_values(int&, int&);
void show_results(int, int);
#endif

用于交换.cpp

    #include <iostream>
    void get_numbers(int& input1, int& input2) {
       using namespace std;
       cout << "Enter two integers: ";
       cin >> input1 >> input2;
    }
    void swap_values(int& variable1, int& variable2) {
        int temp;
        temp = variable1;
        variable1 = variable2;
        variable2 = temp;
    }
    void show_results(int output1, int output2) {
       using namespace std;
       cout << "In reverse order the numbers are: "
       << output1 << " " << output2 << endl;
    }

对于源 3.cpp:

    #include "stdafx.h"
    #include "swap.h"
    int main()
    {
       int first_num, second_num;
       get_numbers(first_num, second_num);
       swap_values(first_num, second_num);
       show_results(first_num, second_num);
       return 0;
    }

当我调试程序时,它说:"无法启动程序'C:\User...'系统找不到指定的文件。我做错了什么?

由于代码编译成功,但无法启动,因此可能存在与调试环境相关的问题。

此外,一旦您拥有#pragma once,您就不需要#ifdef#define#endif

如果您提供的是整个代码,则您没有在swap.cpp中包含swap.h。因此,您有函数的定义,但没有声明。虽然我会想象另一个错误或至少在这里发出警告。尝试解决这个问题。

如果不起作用,请尝试构建发布版本。它编译吗?它开始了吗?当它启动时,它会做任何事情吗?如果我之前提到的是问题所在,我希望程序只是运行到最后,而不做任何事情。

如果问题出在主文件中的swap.h上,请确保它位于同一位置,或者包含路径指向包含它的目录。stdafx.h也是如此

此外,您不需要#pragma once#ifndef #define#endif。摆脱其中任何一个,我建议使用 #ifndef #define#endif ,因为并非到处都支持#pragma once。但对你来说,这无关紧要。