如何在源文件中实现嵌套类构造函数
问题描述:
我在我的主类中有一个名为cell的嵌套类。 I 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::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)
{}
+0
这个工作很好。 – paypaytr
答
你需要让你的内部类公众和方法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;
}
+0
谢谢,但我内心的类必须是私人的,因为某些原因,我不会详细说明。 – paypaytr
'Something :: Cell Cell(int row,...)' - >'Something :: Cell :: Cell(int row,...)'..不在'Something'中, Cell的构造函数是'Cell :: Cell'。在命名空间中,ust前缀为单个'Something ::' – Peter