C++在函数中重用 .h 文件中的相同变量名(this.variable = 变量错误?)
我的 .h 文件中有一个变量的名称,该函数具有相同的名称... 例如:
//computer.h
class Computer{
private:
string computerName;
int cores;
}
//computer.cpp
Computer::Computer(string computerName, int cores)
{
...
}
我想将 .cpp 函数中的值分配给 .h 文件变量。
每当我这样做时,它都不起作用。我做得正确吗?
this.computerName = computerName;
this.cores=cores;
I have a name of a variable in my .h file which a function has the same name...
for example:
//computer.h
class Computer{
private:
string computerName;
int cores;
}
//computer.cpp
Computer::Computer(string computerName, int cores)
{
...
}
I want to assign the values from the .cpp function to the .h file variables.
whenever i do this, it doesn't work. Am I doing it correctly??
this.computerName = computerName;
this.cores=cores;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C++ 中,
this
是一个指针,因此它是:In C++,
this
is a pointer, so it would be:使用初始化代替赋值
是可行的。构造函数初始值设定项列表具有确切的目的。
Instead of assignment, use initialization
Yes that works. Constructor initializer lists have that exact purpose.
如果您发布了实际的错误消息而不是仅仅说“它不起作用”,那么很明显该问题与变量名称无关!
this
是一个指针,因此您应该使用->
运算符,而不是.
。此外,建议通过引用 const 而不是通过值来接受字符串,并且您应该更喜欢初始化而不是赋值;稍后你会发现,对于某些事情(特别是常量),你实际上必须这样做:
If you'd posted the actual error message rather than just saying "it doesn't work", it would become clear that the issue has nothing to do with the variable names!
this
is a pointer, so you should use the->
operator, not.
.Additionally, it's advisable to accept strings by reference-to-const rather than by value, and you should really prefer initialisation over assignment; you'll find later on that for some things (notably, constants) you actually have to do this:
您声明同一个变量两次。
只需将其更改为 Computer::Computer(string computerName, unsigned int numCores),我将使用 unsigned int,而不是 uusing 和 int。
在 C++ 中,this->cores == cores
you are declaring the same variable twice.
just change it to
Computer::Computer(string computerName, unsigned int numCores)
, and instead of uusing and int, I would use an unsigned int.in C++, this->cores == cores