看下面的代码,我很困惑为什么我们需要 getter 和 setter?
#include<iostream>
#include<cstring>
using namespace std;
class car
{
char name[30];
int price;
public:
void get_data(char* n,int p)
{
strcpy(name,n);
price=p;
}
void set_data()
{
cout<<"Name: "<<name<<endl;
cout<<"Price:"<<price<<endl;
}
///Lets add the idea of constructor
car()
{
cout<<"constructor has been called"<<endl;
}
car(char *n, int p)
{
cout<<"2nd constructor has been called"<<endl;
strcpy(name,n);
price=p;
}
~car()
{
cout<<"Name: "<<name<<endl;
cout<<"Price:"<<price<<endl;
}
};
int main()
{
car A("BMW",1000);
car B("Audi",2000);
}
我想问的是,如果构造函数可以设置值并打印值,为什么还需要getter和setter?为什么会有 getter 和 setter 的想法?
我是一名优秀的程序员,十分优秀!