LINKER ERROR LNK1169& LNK2005

时间:2017-09-12 23:13:37

标签: c++ c++11

我正在学习c ++并尝试一次练习翻译单元和其他东西,但我收到标题上列出的错误。这个程序是出于学习目的,我试图解释每个标题和实现文件的用途。

-------- -------- CString.h

#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[]); 

-------- -------- CString.cpp 在构造函数中接收C样式字符串并通过获取前三个字符并将其存储在mystring中以便稍后通过函数display()显示来截断它(

#include <iostream> 
#include "CString.h"
#define NUMBEROFCHARACTERS 3   

using namespace w1; 

w1::CString::CString(char stylestring[]) 
{
if (stylestring[0] == '\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对象,然后通过运算符重载显示可能截断的c风格字符串版本。

#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样式字符串来测试目的。

#include <iostream> 
#include "process.h"

using namespace std; 

int main()
{
char themainstring[] = "hiiiii";
process(themainstring);
return 0;
}

1 个答案:

答案 0 :(得分: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.cppmain.cpp都包含两次包含该定义的文件CString.h(一次编译这两个文件时)。

相关问题