如何在源文件中实现嵌套类构造函数

时间:2017-10-10 08:58:49

标签: c++ inner-classes

我的主类中有一个名为cell的嵌套类。 我c

class Something{
  class Cell
    {
    public:
        int get_row_Number();
        void set_row_Number(int set);

        char get_position_Letter();
        static void set_position_Letter(char set);

        void set_whohasit(char set);
        char get_whohasit();

        Cell(int row,char letter,char whohasit);

    private:
        char position_Letter;
        int row_Number;
        char whohasit;
    };
};

我想在.cpp文件中实现嵌套类构造函数

Something::Cell Cell(int row,char letter,char whohasit){
    Something::Cell::set_position_Letter(letter);
    Something::Cell::set_row_Number(row);
    Something::Cell::set_whohasit(whohasit);
}

但这是错误的。我认为正确的是Something :: Cell :: Something :: Cell,但我不认为那也是真的。

2 个答案:

答案 0 :(得分:7)

几乎那里。它很简单:

Something::Cell::Cell(int row,char letter,char whohasit){
    Something::Cell::set_position_Letter(letter);
    Something::Cell::set_row_Number(row);
    Something::Cell::set_whohasit(whohasit);
}

但实际上,我强烈建议您使用初始化程序,而不是构建未初始化的成员,然后分配给它们:

Something::Cell::Cell(int row, char letter, char whohasit)
    :position_Letter(letter)
    ,row_Number(row)
    ,whohasit(whohasit)
{}

答案 1 :(得分:1)

您需要将内部类设为public,方法set_Position_Letter不能是静态的,因为char position_Letter不是静态的(这里是标题):

class Something
{
public:
    class Cell {
    public:
        int get_row_Number();
        void set_row_Number(int set);

        char get_position_Letter();
        void set_position_Letter(char set);

        void set_whohasit(char set);
        char get_whohasit();

        Cell(int row,char letter,char whohasit);

    private:
        char position_Letter;
        int row_Number;
        char whohasit;
    };
};

这是cpp:

Something::Cell::Cell(int row, char letter, char whohasit) {
    set_position_Letter(letter);
    set_row_Number(row);
    set_whohasit(whohasit);
}

void Something::Cell::set_position_Letter(char set) {
    this->position_Letter = set;
}

void Something::Cell::set_whohasit(char set) {
    this->whohasit = set;
}

void Something::Cell::set_row_Number(int set) {
    this->row_Number = set;
}