C ++从头部定义构造函数

时间:2013-02-19 01:45:17

标签: c++ compiler-errors instantiation unresolved-external lnk2019

class_one.h

#ifndef CLASS_ONE
#define CLASS_ONE
#include <string>

namespace ones{

    typedef enum{BLACK, WHITE, RED} b_color;

    typedef char b_letter;
    const b_letter letters[4] = {'A', 'B', 'C', 'D'};

    class one{
        b_color color;
        b_letter letter;
        public:
        one(b_color, b_letter);
        std::string combo();
        b_color getColor();
        b_letter getLetter();
    };
}
#endif

鉴于此头文件,我应该如何创建.cpp文件,然后如何在另一个文件main.cpp中实例化此类? 我会想到这样的事情:

class_one.cpp

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

using namespace ones;

class one
{
    b_color color;
    b_letter letter;
public:

    one(b_color c, b_letter l) //Not sure about this one..
    {
        color = c;
        letter = l;
    }
    std::string combo()
    {
        return "blahblah temporary. letter: " + letter; //not finished
    }
    b_color getColor()
    {
        return color;
    }
    b_letter getLetter()
    {
        return letter;
    }
};

然后实例化它,我会做这样的事情:

的main.cpp

#include "class_one.h"

int main()
{
    ones::one test(ones::BLACK, ones::letters[0]);
    //cout<<test.name()<<endl;
    return 0;
}

所有内容都是从更大的文件集中提取的,但这是我的问题的基本要点..头文件应该是正确的,但我不确定如何实例化'one'类,而不是使用该构造函数。我认为我在.cpp中定义的构造函数是错误的。我已经习惯了Java,所以我从未见过像头文件中那样的构造函数,如果它甚至是构造函数的话。对我来说,它看起来像method(int, int)而不是我习惯的:method(int a, int b) 运行时我收到此错误:

main.obj : error LNK2019: unresolved external symbol "public: __thiscall ones::one::one(enum ones::b_color, char)" (??0one@ones@@QAE@W4b_color@1@D@Z) referenced in function _main
<path>/project.exe : fatal error LNK1120: 1 unresolved externals

对于我在这里的令人难以置信的愚蠢命名感到抱歉,但它确实有意义。可能是问题代码中的一些输入错误,因为我现在已经手工编写了大部分内容。 任何帮助表示赞赏..

1 个答案:

答案 0 :(得分:2)

您的cpp文件应如下所示:

#include "class_one.h"

ones::one::one(ones::one::b_color c, ones::one::b_color l)
{
    //code here
}

std::string ones::one::combo()
{
   // code here
}

// additional functions...

等等。您没有使用类块重新定义类,您只需指定我在此处显示的各个函数定义。函数定义格式应该是这样的:

[return type] [namespace]::[class]::[function]([parameters])
{
    // code here
}

看起来你在实例化方面做得很好。您也不必重新声明成员变量。

相关问题