Вопрос

I am a complete beginner at C++ and what might seem stupidly obvious to you I just cannot get my head around.

Testapp.h

#ifndef TESTAPP_H
#define TESTAPP_H
using namespace std;
class Testapp {
private: 
public:
Testapp() { };   
};
#endif

main.cpp

#include <cstdlib>
#include <iostream>
#include "Testapp.h"
Testapp::Testapp(){
}
int main(int argc, char *argv[])
{
system("PAUSE");
return EXIT_SUCCESS;
}

Error Message: Redefinition of 'Testapp::Testapp()'

At a guess it's defining the constructor twice, how to overcome this though I am not sure. I am using DEV-C++.

Это было полезно?

Решение

A function declaration is also a definition when it gives the implementation or body of the function. You have a definition of the constructor in your class definition that looks like this:

Testapp() { };  

It's body is { } and is empty. Then you have another definition in your main.cpp file that looks like this:

Testapp::Testapp(){
}

Again, this function definition has an empty body. Just because the function implementations are exactly the same, it doesn't mean it's okay. Under the one definition rule, you must not have multiple definitions of a function. An easy fix is to make the one in the class definition only a declaration by not providing a body:

Testapp();

Alternatively, you could just get rid of the definition in main.cpp entirely. Exactly what you end up doing depends on how you want to lay out your code. A typical approach is to have a header file containing the class definition and member function declarations, Testapp.h:

#ifndef TESTAPP_H
#define TESTAPP_H
using namespace std;
class Testapp {
private: 
public:
Testapp(); // Just a declaration
};
#endif

Then in an implementation file for this class, Testapp.cpp, give the member function definitions:

#include "Testapp.h"

Testapp::Testapp() { }

Then in main.cpp, just include the header file and use the class it defines:

#include "Testapp.h"

int main(int argc, char *argv[])
{
  Testapp test;
  return 0;
}

I recommend removing the using namespace std; from your header file. It's considered pretty bad practise even in source files for polluting your global namespace, but this becomes positively infectious if you do it in your header file.

Другие советы

In your header file, you only want to write a function "stub", or function prototype:

class Testapp {
  private: 
  public:
  Testapp();   
};

You need to learn the difference between function declarations (prototypes) and function definitions in C++.

You have already defined Testapp::Testapp in your class declaration

Testapp() { };   

You need to either remove

Testapp::Testapp(){
}

Or change constructor definition to declaration

Testapp();   

It's indeed defined twice - once in the Testapp.h and once in the main.cpp, just remove one of them.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top