1

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;
    }
};

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

主文件

#include "class_one.h"

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

一切都是从更大的文件集群中提取的,但这是我问题的要领。头文件应该是正确的,但我不确定如何实例化“一个”类,而不是使用该构造函数。我认为我在 .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

很抱歉我在这里有一个非常愚蠢的命名,但它确实有意义。问题代码中可能有一些输入错误,因为我现在大部分都是手工编写的。任何帮助表示赞赏..

4

1 回答 1

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
}

看起来你很擅长实例化。您也不必重新声明成员变量。

于 2013-02-19T01:49:38.490 回答