C++的C#等式是什么::(非静态)
本文关键字:静态 是什么 C++ | 更新日期: 2023-09-27 18:01:09
我使用C++已经有一段时间了,几周前我学会了C#。在编写初始化程序时,我发现我不知道如何使用::运算符。
在C++中,它看起来像:
class something{
bool a;
void doSg();
}
void doSg(){
something::a = true;
}
int main()
{
something mySg;
mySg.doSg();
}
因此,我尝试在C#中重新创建void doSg()
函数:一个修改类对象被调用的数据的方法。在以下代码中:
class something
{
bool a;
public void func()
{
this.a = true;
}
}
class source
{
something mySg;
mySg.func();
}
this.a = true
有效吗,或者我应该制作:
class something
{
bool a;
public myclass func(myclass item)
{
item.a = true;
return item;
}
}
class source
{
something mySg;
mySg = func(mySg);
}
或者有更好的解决方案吗?
var这里有一个关键字,所以它可能不会像你使用它那样工作。你可以这样做:
class something {
bool myBool;
public void func()
{
this.myBool= true;
myBool= true; //or you can just leave this "this" off
}
}
当调用something.func((时,它会将myBool设置为true。
"this"只是指类(或结构(本身,不需要经常使用。你只需要它在有重复的名字这样的情况下。。。
class something {
bool myBool;
public void func(bool myBool)
{
myBool= myBool; //would not do anything
this.myBool= myBool; //force class myBool
}
}
至于return,您列出的第二个示例需要它,但需要更改或删除var。
class something
{
public Myclass func(myclass item)
{
Myclass item = new myClass(); // first create a class
return item; //since myclass in in the header, we need to return a myclass
}
}
我将myClass更新为myClass,因为类应该以标题开头,但这不是必需的。我希望这对一些人有所帮助。当涉及到所有细节时,C#与C++不同。