我的二传手在新类中不起作用(继承)

My setter doesn't work in new class (inheritance)

本文关键字:继承 不起作用 新类中 二传手 我的      更新时间:2023-10-16

这是我的代码。我创建了基类并在构造函数中设置 x=0。接下来我用了virtual set_x() = 0.我在新类中创建了set_x()。输出:

set x100DONE. Let's check. 0500

为什么我得到 0500 而不是 100500?

#include "mainwindow.h"
#include <QApplication>
#include <fstream>
#include <string>
#include <iostream>
using namespace std;
struct invalid_file_handler : std::runtime_error{
using runtime_error::runtime_error;
};
class base_class{
private:
int x;
int y;
public:
virtual void set_x()=0;
void set_y(){
this->y=500;
}
int get_x(){
return (this->x);
}
int get_y(){
return (this->y);
}
base_class(){
this->x=0;
this->y=0;
}
};
class new_class :public base_class{
public:
void set_x();
private:
int z;
int x;
int y;
};
void new_class::set_x(){
cout << "set x " << endl;
this->x=100;
cout << this->x << endl << "DONE. Let's check.  ";
}
int main()
{
ifstream my_open_file;
string file_path = "/home/wojtek/Pulpit/elo.odt";
try{
my_open_file.open("/home/wojtek/Pulpit/elo.odt");
my_open_file.close();
}catch (std::runtime_error &e){
cerr << "Hello Xd XD chua" << endl;
cerr << e.what();
}
ofstream myfile;
try{
myfile.open ("/home/wojtek/Pulpit/example.txt");
myfile << "Writing this to a file.n";
myfile.close();
}
catch(invalid_file_handler &e){
cerr << "Hello!" << endl;
}
new_class *object = new new_class();
object->set_x();
cout << object->get_x();
object->set_y();
cout << object->get_y();
//base_class object;
//cout << object.get_y();
return 0;
}

new_class中声明的变量xy正在隐藏具有相同名称的变量base_class中声明的变量。这意味着在任何new_class的成员方法中,名称x指的是new_class::x而不是base_class::x

只需从new_class定义中删除这些行:

int x;
int y;

并在base_classprotected中使用相同的成员而不是private,以便new_class也可以访问:

class base_class{
protected:
int x;
int y;

注意:您的代码存在内存泄漏,因为您在分配后永远不会delete object。始终deletenew的内容,除非你真的需要,否则不要使用new