【问题标题】:How to implement Nested Class Constructor in Source file如何在源文件中实现嵌套类构造函数
【发布时间】:2017-10-10 08:58:49
【问题描述】:

我的主类中有一个名为 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,但我也不认为这是真的。

【问题讨论】:

  • Something::Cell Cell(int row, ...) -> Something::Cell::Cell(int row, ...).. 如果不在 Something 中,Cells 的构造函数将是 Cell::Cell。在命名空间中,我们必须在所有这些前面加上一个 Something::

标签: c++ inner-classes


【解决方案1】:

几乎在那里。很简单:

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)
{}

【讨论】:

    【解决方案2】:

    你需要将你的内部类公开,并且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;
    }
    

    【讨论】:

    • 谢谢,但由于某些原因,我的内部课程必须是私有的,我不会详细说明。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    相关资源
    最近更新 更多