int main() {
Dog d;
d.setAge(4);
d.setWeight(12);
d.setColor("Black");//输入字符串
cout << d.getAge() << endl;
cout << d.getWeight() << endl;
cout << d.getColor() << endl;//输出字符串
d.speak();
return 0;
}
如何在类中进行字符串的输入输出
Dog类字符串的输入输出
1.私有域定义
private:
char *color;
2.构造函数初始化
给color分配空间
Dog() {
cout << "Constructor in Dog." << endl;
color = new char[20];//初始化color
}
3.析构函数
释放空间
~Dog() {
cout << "Destructor in Dog."<<endl ;
delete[] color;
}
4.类中输入color
void setColor(const char *c) {
strcpy(color, c);
}
5.类中输出color
const char *getColor() {
return color;
}
所有代码如下
#include <iostream>
#include <string.h>
using namespace std;
class Mammal {
private:
int age;
double weight;
public:
Mammal() {
cout << "Constructor in Mammal." << endl;
}
~Mammal() {
cout << "Destructor in Mammal." << endl;
}
void setAge(int a) {
age = a;
}
void setWeight(int b) {
weight = b;
}
int getAge() {
return age;
}
double getWeight() {
return weight;
}
};
class Dog : public Mammal {
private:
char *color;
public:
Dog() {
cout << "Constructor in Dog." << endl;
color = new char[20];//初始化color
}
~Dog() {
cout << "Destructor in Dog."<<endl ;
delete[] color;
}
void speak() {
cout << "Dog sound wang,wang,wang!" << endl;
}
void setColor(const char *c) {
strcpy(color, c);
}
const char *getColor() {
return color;
}
};
int main() {
Dog d;
d.setAge(4);
d.setWeight(12);
d.setColor("Black");
cout << d.getAge() << endl;
cout << d.getWeight() << endl;
cout << d.getColor() << endl;
d.speak();
return 0;
}
输入输出用例