在 C++ 中处理不同的文件
work with different files in c++
你好,我有一个简单的程序,有一个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
头文件添加到您的文件中
相关文章:
- 出色的文件处理能力
- C++中的文件处理:更新行
- 文件处理,eof() 定义
- C++网络 IO、文件处理和网络故障
- 如何使用自定义对象的序列化在 c++ 中编写自定义二进制文件处理程序
- ios::app 和 ios::noreplace 模式在文件处理中有什么区别?
- 我将如何在C++中文件处理对象(存储/导入)
- 如何为多个文件处理选择最佳的I/O策略
- read() 的参数类型,用于 c++ 中的文件处理
- STD :: FSTREAM文件处理重复使用的问题
- C 文件处理打开
- 将文件处理作为参数
- 如何在 C++ 中的文件处理中删除文件
- 文件处理I/O C 错误
- 在 c++ 的文件处理中什么是 tellg(),它是如何工作的?
- 循环的文件处理
- c++中数据文件处理中的分段错误
- 数据文件处理-查找文件中的字数
- 文件处理 - 错误:与 while 循环 (C++) 中的"运算符>>"不匹配(代码::块)
- 使用.rose(文件扩展)CPP的文件处理