c++ - 我无法使用继承 setter 和 getter 返回 const char * 变量

标签 c++ inheritance getter-setter

我可以在 setter 函数中打印正确的值,但是当我尝试使用 getter 返回相同的变量时,没有输出。这是我的代码。有人知道我如何更正我的代码吗?

class Student {
public:
    char age;
    double height;
    double gpa;

    int getAge();
    void setAge(int *);
protected:
    const char * name;
 };

class Male :Student {
 public:
 void setName(const char * s);
 const char * getName();
};

void Male::setName(const char * s){
const char* name = s;
std::cout << name << std::endl;
}

const char* Male::getName() {
 return name; //I can't return the value of variable name.
 std::cout << name << std::endl;
}

 void Student::setAge(int* c) {
 age = *c;
}

int Student::getAge() {
 return age;
}

int main() {
 Student jason;
 Male myName;
 int edad = 30;
 jason.height = 162;
 jason.gpa = 1.5;

 jason.setAge(&edad);
 myName.setName("James");

std::cout << jason.height << "\n" << jason.getAge() << "\n" << jason.gpa << "\n" << std::endl;
system("pause");
return 0;
}

不知道为什么不能返回const char变量。 :(

最佳答案

void Male::setName(const char * s) {
  name = s;
  std::cout << name << std::endl;
}

需要将s设置为成员变量name,而不是在方法中创建局部变量

关于c++ - 我无法使用继承 setter 和 getter 返回 const char * 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50034651/

相关文章:

c++ - 在 Eclipse 中,将宏重新定义视为错误而不是警告

c++ - 使用 boost::asio::spawn 生成的 asio 处理程序中的 boost::property_tree::read_xml 段错误

c++ - 为什么按值返回的未命名对象在调用其转换运算符之前会被破坏?

c++ - 哪种设计模式最合适?

java - java中的接口(interface)和继承

c# - UWP C# - 为什么 NotifyPropertyChanged 在这种情况下不触发?

java - 不同java文件中的Getter Setter方法

C++ Primer 第 5 版 第 17.5.3 章 fstream 不换行

c++ - 继承的 protected 默认构造函数不可访问

coldfusion - 不是为我创建的隐式 Getter 和 Setter