c++ - 当我将 C++ 类拆分为 header 和实现时,我收到 20 个没有意义的编译器错误

标签 c++

我按照惯例将程序分成头文件和实现文件,但是,当我尝试运行代码时,出现了大量编译错误。这似乎是我的电脑或IDE的问题,但我以前没有见过。这应该相对简单,因为它是一个类(class)项目。 代码如下:

colorPicker.h

#pragma once
class colorPicker {
private: 
    string colorArray[7];
public: 
    colorPicker(); 
    void printAllColors(); 
    string randomColor(); 
};

颜色选择器.cpp

#include "colorPicker.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std; 



colorPicker::colorPicker() {
    colorArray[0] = "Red"; 
    colorArray[1] = "Green";
    colorArray[2] = "Purple";
    colorArray[3] = "Yellow";
    colorArray[4] = "Orange";
    colorArray[5] = "Indigo";
    colorArray[6] = "Pink";
}

void colorPicker::printAllColors() {
    for (int i = 0; i < 7; i++) {
        cout << colorArray[i] << endl;
    }
}

string colorPicker::randomColor() {
    srand((unsigned)time(0)); 
    int j = 0; 
    j = rand() % 7; 
    return colorArray[j];
}

main.cpp

#include "colorPicker.h"
#include "stdafx.h"
#include <iostream>
#include <string>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>
using namespace std;


int main() {
    colorPicker p;
    p.printAllColors(); 
    cout << "Random Color: " << p.randomColor() << endl; 
    system("pause");
    return 0; 
 }

编译器给出了 20 个错误,但是,它们似乎都源于两个未声明的标识符,而这两个标识符是最明确声明的。我不知道我能做些什么来解决这个问题,这个项目将于周日到期。谢谢。

以下是错误信息 Tons of Errors

最佳答案

您需要在 colorPicker.cpp#include "colorPicker.h"。每个 .cpp 文件基本上由编译器独立处理,并且它们都在最后由“链接器”连接。当编译器查看 colorPicker.cpp 而不包含相应的 header 时,它会丢失您正在使用的所有类的定义。

关于c++ - 当我将 C++ 类拆分为 header 和实现时,我收到 20 个没有意义的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44857056/

相关文章:

C++,linux,如何从字符串中有效地 pop_back() 一个非 latin1 字符

c++ - 为什么 std::adressof() 在无效输入时表现如此?

c++ - gRPC 和 etcd 客户端

c++ - 如何将变量从 main 传递给信号和槽宏?

java - 从 Java 使用 C# 编写的 DLL

c++ - 为什么递归中的 std::ofstream 没有按预期工作?

C++传递函数指针

c++ - 试图理解调车场算法

c++ - OpenNI: "Open failed: Device is in safe mode. Cannot start any stream!"

c++ - 有没有更快的方法在 SIMD 上乘以 2(不使用乘法)?