constref.cpp

来自「压缩包里有教材<<C++模式设计-基于QT4开源跨平台开发框架&gt」· C++ 代码 · 共 35 行

CPP
35
字号
class Person {public:    void setNameV( QString newName) {        newName += " Smith";  /* Changes a temporary that's            about to be destroyed. */        m_Name = newName;    }    void setNameCR( const QString& newName) {//      newName += " Python"; /* Error: can't change const&. */        m_Name = newName;    }    void setNameR( QString& newName) {        newName += " Dobbs"; /* changes the original QString */        m_Name = newName;    }private:    QString m_Name;};int main() {    Person p;    QString name("Bob");    p.setNameCR(name);  /* No temporaries are created. */ //  p.setNameR("Monty");  /* Error: cannot convert to a QString&. */    p.setNameCR("Monty");  /* char* converts to temporary        and gets passed by const reference. */    p.setNameV("Connie");  /* Temporary QString #1 is created to        convert char* to QString. Temporary #2 is created when it is        passed by value. */    p.setNameR(name);      /* No temporaries are created. */    cout << name;         }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?