c++ - C++ 中的类和头文件

标签 c++ xcode class header-files

为什么 Xcode 给我“重新定义控制台”错误? header 和 cpp 中的名称不应该相同吗?

代码如下:

ui.cpp:

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

    }
};

ui.h:

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

主要.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?

不,.cpp 文件应该有实现,而不是声明。这看起来像:

#include "ui.h"

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

请注意,您可能还应该 include guards在您的 .h 文件中以防止它们被多次包含。

关于c++ - C++ 中的类和头文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29308261/

相关文章:

python - python中的牌组卡类

c++ - 为什么在引用类型上使用新的放置会给我带来段错误,即使使用 std::launder 也是如此?

c++ - 断言、-NDEBUG 和段错误

xcode - 完全卸载两个版本的 Xcode

iphone - 目标没有有效的分布配置文件

jQuery 将具有多个类的元素的 1 个类更改为不同的类(a、b、c 更改为 a、b、d)

c++ - printf 到控制台窗口和文件?

c++ - 将多维数组(最初未定义其维度)传递给 C++ 中的函数

ios - 如何从xcdatamodel生成类图?

java - 我应该将 Java 中的静态嵌套类重构为单独的类吗?