【问题标题】:Multiple declarations of a constructor in C++C++中构造函数的多个声明
【发布时间】:2015-11-28 21:35:33
【问题描述】:

我正在为一门课做作业,我遇到了(我认为是)一个基本问题我尝试查看其他答案,但似乎找不到我的问题。

当我运行命令 make 时,我收到以下错误:

    prog8lib.o: In function `Transform':
   .../prog8lib.cc:6: multiple definition of `Transform::Transform(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
    prog8.o:.../prog8lib.cc:6: first defined here
    prog8lib.o: In function `Transform':
   .../prog8lib.cc:6: multiple definition of `Transform::Transform(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::basic_string<char, std::char_traits<char>, std::allocator<char> >)'
    prog8.o:.../prog8lib.cc:6: first defined here

这是我目前正在使用的代码。谁能发现我的错误?

谢谢!!!

prog8.cc:

#include <iostream>
#include <string.h>
#include <stdlib.h>

#include "prog8lib.cc"

using namespace std;

int main(int argc, char** argv) {
    string start = argv[1];
    string end = argv[2];
    Transform(start, end);
}

prog8lib.cc:

#include <iostream>
#include <string>
#include <stdlib.h>
#include "prog8lib.h"

Transform::Transform(string startWord, string endWord) {
    cout << "Test" << endl;
}
Transform::~Transform() {}

prog8lib.h:

#ifndef PROG8LIB_H
#define PROG8LIB_H

#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;

class Transform{
private:
    string start;
    string end;
public:
    Transform(string str, string str2);
    ~Transform();
};

#endif

生成文件:

OBJ = prog8.o prog8lib.o
OPTS = -g -c -Wall -Werror

trans: $(OBJ)
        g++ -o trans $(OBJ)

prog8.o: prog8.cc
    g++ $(OPTS) prog8.cc

prog8lib.o: prog8lib.cc prog8lib.h
        g++ $(OPTS) prog8lib.cc

clean:
        rm -f *.o *~

【问题讨论】:

  • 在 prog8.cc 中,您包含了 proglib8.cc,而不是 .h

标签: c++ makefile multiple-definition-error


【解决方案1】:

改变

#include "prog8lib.cc"

prog8.cc

#include "prog8lib.h"

否则编译器会找到Transform::Transform的两个定义:一次在prog8.cc,一次在proglib8.cc

【讨论】:

    【解决方案2】:

    您已经在头文件中声明了一个类,这是您需要包含在 main.cpp 中的文件。始终包含头文件,而不是 .cpp 文件。..

    http://stackoverflow.com/questions/333889/why-have-header-files-and-cpp-files-in-c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多