1 类内部实现初始化
#include <iostream>
#include <string>
using namespace std;
/**
* Class setter, getter.
* @author xindaqi
* @since 2020-10-24
* */
class Phone {
private:
string os;
string brand;
public:
Phone(string os, string brand) {
this->os = os;
this->brand = brand;
}
void setOs(string os) {
this->os = os;
}
string getOs() {
return os;
}
void setBrand(string brand) {
this->brand = brand;
}
string getBrand() {
return brand;
}
};
int main() {
Phone *phone = new Phone("ios", "iphone");
cout<< "Phone OS: " << phone -> getOs() <<endl;
cout<< "Phone brand: " << phone -> getBrand() <<endl;
cout<<"============="<<endl;
phone -> setOs("iOS");
phone -> setBrand("iPhone");
cout<< "Phone OS: " << phone -> getOs() <<endl;
cout<< "Phone brand: " << phone -> getBrand() <<endl;
return 0;
}
- 结果
Phone OS: ios
Phone brand: iphone
=============
Phone OS: iOS
Phone brand: iPhone
2 类外部实现初始化
#include <iostream>
#include <string>
using namespace std;
/**
* Class setter, getter.
* @author xindaqi
* @since 2020-10-24
* */
class Phone {
private:
string os;
string brand;
public:
Phone(string os, string brand);
void setOs(string os);
string getOs();
void setBrand(string brand);
string getBrand();
};
Phone::Phone(string os, string brand) {
this->os = os;
this->brand = brand;
}
void Phone::setOs(string os) {
this->os = os;
}
string Phone::getOs() {
return os;
}
void Phone::setBrand(string brand) {
this->brand = brand;
}
string Phone::getBrand() {
return brand;
}
int main(){
Phone *phone1 = new Phone("iOS", "iPhone");
cout<<"Phone OS: " << phone1->getOs() << endl;
cout<< "Phone brand: " << phone1->getBrand() << endl;
cout<<"============="<<endl;
phone1->setOs("iOS");
phone1->setBrand("iPhone");
cout<<"Phone OS: " << phone1->getOs() << endl;
cout<< "Phone brand: " << phone1->getBrand() << endl;
cout<<"============="<<endl;
Phone phone2("iOS", "iPhone");
cout<<"Phone OS: " << phone2.getOs() << endl;
cout<< "Phone brand: " << phone2.getBrand() << endl;
return 0;
}
- 结果
Phone OS: iOS
Phone brand: iPhone
=============
Phone OS: iOS
Phone brand: iPhone
=============
Phone OS: iOS
Phone brand: iPhone
3 小结
- 类私有成员赋值使用getter和setter方法有两种实现方式:类内部直接实现函数,类外部实现函数.
- 类私有成员变量初始化,可使用析构函数也可以在类内部初始化.
[参考文献]
[1]http://c.biancheng.net/view/2221.html
[2]https://blog.csdn.net/qq78442761/article/details/80797561
[3]https://blog.csdn.net/hhyvs111/article/details/78786249