这是我的代码。我创建了基类,并在构造函数中设置了x = 0。接下来,我使用了virtual set_x() = 0
。我在新类中创建了set_x()。输出:
set x
100
DONE. 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;
}
答案 0 :(得分:1)
在x
中声明的变量y
和new_class
是{em> shadowing 在base_class
中声明的具有相同名称的变量。这意味着在new_class
的任何成员方法中,名称x
指的是new_class::x
,而不是 base_class::x
。
只需从new_class
定义中删除这些行:
int x;
int y;
并在base_class
protected
中创建相同的成员,而不是private
,以便new_class
也具有访问权限:
class base_class{
protected:
int x;
int y;
注意:您的代码存在内存泄漏,因为分配代码后从未delete object
。始终delete
new
,除非您确实需要,否则不要使用new
。