this->age = age是啥意思?
时间: 2024-03-29 16:37:28 浏览: 15
this->age = age这行代码表示将当前对象的成员变量age的值设置为参数age的值。其中,this->age表示当前对象的成员变量age,而age则是传入的参数。这种语法常用于成员函数的实现中,用于区分成员变量和函数参数同名的情况。通过使用this指针来明确指出是访问当前对象的成员变量age,而不是参数age。
相关问题
c++ Stu& operator=(const Stu& other) { this->name = other.name; this->age = other.age; cout << "=号运算符重载函数" << endl; return *this; }啥意思
这是一个 C++ 中的类 Stu 的赋值运算符重载函数。其作用是将一个 Stu 类型的对象的值赋给另一个 Stu 类型的对象。
函数的参数 `const Stu& other` 是一个常量引用,表示传入的另一个对象的引用,避免了进行拷贝构造函数的开销。
函数体中的代码 `this->name = other.name; this->age = other.age;` 表示将参数 `other` 对象的 `name` 和 `age` 成员变量的值分别赋值给当前对象的 `name` 和 `age` 成员变量。
最后,函数返回一个指向当前对象的引用 `return *this`,用于支持链式赋值操作。
在函数体中的 `cout << "=号运算符重载函数" << endl;` 用于输出一条信息,表示这个函数被调用了。
#include<iostream> #include<string> using namespace std; class employee { private: string name; int age; double salary; public: employee(string name="",int age=0,double salary=0) { this->name = name; this->age = age; this->salary = salary; } void setname(string name){ this->name = name; } void setage(int age) { this->age = age; } void setsalary(double salary) { this->salary = salary; } void display() { cout << "姓名:" << name << endl; cout << "年龄:" << age << endl; cout << "工资:" << salary << endl; } string getname() { return name; } int getage() { return age; } double getsalary() { return salary; } }; int main() { employee emp("王鹏",18,18000); emp.display(); emp.getname("王赟煜"); emp.setsalary(200000); emp.display(); return 0; }怎么修改程序
你需要将 `emp.getname("王赟煜");` 修改为 `emp.setname("王赟煜");`,因为 `getname()` 是获取姓名的函数,而不是设置姓名的函数。修改后的程序如下:
```
#include<iostream>
#include<string>
using namespace std;
class employee {
private:
string name;
int age;
double salary;
public:
employee(string name="",int age=0,double salary=0) {
this->name = name;
this->age = age;
this->salary = salary;
}
void setname(string name){
this->name = name;
}
void setage(int age) {
this->age = age;
}
void setsalary(double salary) {
this->salary = salary;
}
void display() {
cout << "姓名:" << name << endl;
cout << "年龄:" << age << endl;
cout << "工资:" << salary << endl;
}
string getname() {
return name;
}
int getage() {
return age;
}
double getsalary() {
return salary;
}
};
int main() {
employee emp("王鹏",18,18000);
emp.display();
emp.setname("王赟煜");
emp.setsalary(200000);
emp.display();
return 0;
}
```