c++ Classes Mutators 无返回值

问题描述 投票:0回答:0

我想知道如何在不返回任何内容或通过引用传递参数的情况下将私有变量分配给一个值。例如:

#include <iostream>

using namespace std;

class Test{
    public: 
        void setName(string nameParam);
        string getName() const;
    private:
        string name;
    
};

void Test:: setName(string nameParam){
    name = nameParam;
}

string Test:: getName() const{
    return name;
}


int main()
{
    Test test;
    test.setName("Zach");
    cout << test.getName() << endl;

    return 0;
}

这将编译并运行良好,我只是不明白 setName 函数如何在不返回字符串或没有参数为 &nameParam(通过引用传递)的情况下更新“名称”。

我原以为它什么都不做,然后当你返回名字时你会得到随机垃圾,但程序运行良好。

c++ function class reference void
© www.soinside.com 2019 - 2024. All rights reserved.