如何声明字符串名称、int年龄和字符串位置



我是c++类的新手,收到消息说我的变量名、年龄和位置没有定义。我该怎么解决这个问题?有人能给我解释一下吗

#include <iostream>
using namespace std;
class Animal {
private:
string  n;
int a;
string s;
public:
void set_data(string name, int age, string location ) {
n = name;
a = age;
s = location;
}
};
class  Zebra : public Animal {
public:
void message_zebra() {
cout << "The Zebra name is  " <<name<<"and the age  is" << age << "and the location is " << location;
}
};
class Dolphin : public Animal {
public:
void message_dolphin() {
cout << "The Dolphin name is  " << name << "and the age  is" << age << "and the location is " << location;
}
};
int main() {
Zebra zeb;
Dolphin dol;
zeb.set_data("Milly", 22, "hawaii");
dol.set_data("Kyle", 22, "detroit");
zeb.message_zebra();
dol.message_dolphin();
}

您不能访问父类的私有成员变量。如果要访问父类的变量,则必须将它们定义为受保护的或公共成员变量。

此外,您应该使用父成员变量名称,如nas。不是nameagelocation

class Animal {
protected: // updated part
string  n;
int a;
string s;
public:
void set_data(string name, int age, string location ) {
n = name;
a = age;
s = location;
}
};
class  Zebra : public Animal {
public:
void message_zebra() {
cout << "The Zebra name is  " << n <<"and the age  is" << a << "and the location is " << s;
}
};
class Dolphin : public Animal {
public:
void message_dolphin() {
cout << "The Dolphin name is  " << n << "and the age  is" << a << "and the location is " << s;
}
};

有三个问题。

  1. #include <string>
  2. 如上所述;private:";至";protected:">
  3. cout应该使用声明的成员变体
cout << "The Zebra name is " << n <<"and the age is" << a << "and the location is " << s; 

最新更新