我正在学习C ,并尝试一次练习翻译单元和其他内容,但是我会在标题上列出错误。该程序是出于学习目的,我试图解释每个标题和实现文件应该做的。
-----------------------------
#ifndef CSTRING_H
#define CSTRING_H
#include <iostream>
namespace w1
{
class CString
{
public:
char mystring[];
CString(char cstylestring[]);
void display(std::ostream &os);
};
std::ostream &operator<< (std::ostream &os, CString &c)
{
c.display(os);
return os;
}
}
#endif
-------- process.h -------- - 过程函数原型
void process(char cstylestring[]);
--------------------------------------------------------------------------------------------------------------------要在构造函数中接收一个C风格的字符串,并通过拿起前三个字符并将其存储在mystring中,以后通过函数显示()
将其存储在mystring中#include <iostream>
#include "CString.h"
#define NUMBEROFCHARACTERS 3
using namespace w1;
w1::CString::CString(char stylestring[])
{
if (stylestring[0] == ' ')
{
mystring[0] = ' ';
}
else
{
for (int i = 0; i < NUMBEROFCHARACTERS; i++)
{
mystring[i] = stylestring[i];
}
}
//strncpy(mystring, stylestring, NUMBEROFCHARACTERS);
}
void w1::CString::display(std::ostream &os)
{
std::cout << mystring << std::endl;
}
--------- process.cpp --------接收C风格的字符串并创建CSTRING对象,然后通过Operator Overloading显示C-Style字符串的截断版本。
#include "process.h"
#include "CString.h"
#include <iostream>
using namespace std;
void process(char cstylestring[])
{
w1::CString obj(cstylestring);
std::cout << obj << std::endl;
}
--------- main.cpp --------测试目的,通过将C风格字符串发送到Process函数。
#include <iostream>
#include "process.h"
using namespace std;
int main()
{
char themainstring[] = "hiiiii";
process(themainstring);
return 0;
}
<<
运算符已定义多个时间,因为您将其定义为从多个源文件中包含的标头文件中定义。
添加inline
修改器,以便仅保留一个副本,或者在一个源文件中移动定义(仅保留在标题文件中)。
正如我在评论中提到的那样,该程序将在运行时崩溃,因为没有为mystring
分配内存。如果应为4个字符的最大长度,则可以像以下内容一样在方括号内添加4个。
char mystring[4];
否则,如果您需要可变大小,则使用std::vector
之类的东西可能会避免明确的内存管理。
更新:
我的原始答案完成了 我说的是 CString.h
中的以下定义:std::ostream &operator<< (std::ostream &os, CString &c)
{
c.display(os);
return os;
}
process.cpp
和 main.cpp
都包含文件CString.h
,其中包含该定义两次(一次编译这两个文件中的每一个)。