C :方法中的字符串成员别名



我的构造函数:

bnf::bnf(string encoded)
{
    this->encoded = encoded;
}

将字符串数据复制到成员。(或者是..?)

我将有一个递归解码方法,但希望始终避免编写this->encoded

我如何有效地创建对方法中成员的别名/引用?

这是否可以最好地避免开销?

您只需传递其他命名参数即可。这是假设encoded是您的bnf类的私有字符串成员

bnf::bnf(string en)
{
    encoded = en;
}

在您的其他功能中,如果您不想:

,您仍然不需要编写this
void bnf::printCode(){
     cout << encoded << endl;
}

假设您的班级看起来像这样:

class bnf{
    public:
         bnf(string en};
         void printCode();
         //<some other functions>
    private:
         string encoded;
}

您现在正在做的事情没有错。表达,清晰和正确。不要试图破坏它。

如果您担心使用this指针"开销",则不要:它已经尽可能高效。从字面上看,没有办法更快。

如果您的问题有点错了,您要做的就是提及成员函数中的成员变量,则:

struct MyClass
{
   int x;
   void myFunction();
};
void MyClass::myFunction()
{
   this->x = 4;
}

该功能等效于:

void MyClass::myFunction()
{
   x = 4;
}

最新更新