简体   繁体   中英

Classes and headers in C++

Why Xcode gives me "Redefinition of Console" error? Should not be the same name in the header and cpp ?

Here is the code:

ui.cpp:

#include "ui.h"
    class Console {
    public:
    void run() {
        puts("Hello my friend!");

    }
};

ui.h:

class Console {
public:
    void run();
};

main.cpp:

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

int main(int argc, const char * argv[]) {
    Console c;
    c.run();
return 0;
}

Should not be the same name in the header and cpp?

No, the .cpp file should have the implementations, not the declaration. This would look like:

#include "ui.h"

void Console::run() {
    puts("Hello my friend!");
}

Note that you also probably should include guards in your .h file to prevent them from being included multiple times.

Classes are defined in header files. The .cpp should contain the implementation of the functions, not the class definition.

ui.cpp should be:

#include <stdio.h>    /* for puts */
#include "ui.h"

void Console::run() {
    puts("Hello my friend!");
}

If you're learning C++, try a tutorial like http://www.learncpp.com/ .

Because you redefined it. Literally right there in your code.

To define one of its member functions, you do just that , without repeating the class's definition:

#include "ui.h"

void Console::run()
{
   puts("Hello my friend!");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM