在 C++ 中处理不同的文件

work with different files in c++

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

你好,我有一个简单的程序,有一个main.cpp一个a.h和一个a.cpp。我想在 a 中定义一个类.cpp并简单地调用该类的方法main.cpp

我的a.h

#include <iostream>
using namespace std;
class Hello 
{
 string hello();
};

我的.cpp

#include "a.h"
#include <iostream>
string class Hello::hello(){return "hello world";};

我的主.cpp

#include "a.h"
 int main()
 {
  Hello h;
  cout << h.hello();

 }

编辑:将include"a.cpp"更改为a.h并将字符串添加到方法hello的定义中。 将#include <string>添加到 a.h

编译时出现错误

"A.cpp:4:22:错误:"类 Hello"中的"hello"未命名类型 字符串类 Hello::hello() {return "Hello";};"

"A.cpp:4:28:错误:')' 标记之前的预期非限定 ID 字符串类 Hello::hello() {return "Hello";};"

一个简单的问题,你已经声明了一个函数作为类的一部分:

class Hello {
// ^Function is part of the class Hello.
string hello();
// ^Function returns a string
//      ^Function is called "hello"
//           ^Function takes no arguments.

因此,当您定义函数时,您需要为编译器提供相同的信息:

string Hello::hello() {
// ^Function returns a string
//      ^Function is part of the class Hello
//             ^Function is called "hello"
//                  ^Function takes no arguments.   
  • 您还需要将标头<string>添加到文件中,以方便使用 string 对象。
  • 你的'#include "a.cpp"需要#include "a.h",经验法则是你永远不应该看到#include file.c/cpp
  • 最后,您需要将函数设为hello公共,以允许其在类成员之外使用。

这是一个活生生的例子供您使用。

但我能给出的最好的建议是拿起一本 c++ 初学者的书。它会给你一个美好的世界。权威C++书指南和清单

class Hello::hello(){return "hello world";};   // Replace it 
      // with
string Hello::hello(){return "hello world";};  // hello() has string return-type

另外,string头文件添加到您的文件中