我的二传手在新类中不起作用(继承)
My setter doesn't work in new class (inheritance)
这是我的代码。我创建了基类并在构造函数中设置 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;
}
new_class
中声明的变量x
和y
正在隐藏具有相同名称的变量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
。
相关文章:
- 为什么在保护模式下继承升级不起作用
- 将复制构造函数设置为默认值在继承自 QObject 时不起作用
- 带有此指针的模板类多重继承构造函数不起作用?
- 我的二传手在新类中不起作用(继承)
- GCC:当层次结构中存在虚拟继承时,C++11 内联对象初始化(使用 "this")不起作用
- 为什么多个头文件和源文件中的C++继承不起作用?
- C++ 多级继承不起作用
- C++,继承的复制因子不起作用
- C++为什么继承不起作用
- 在C++中实现方法时继承不起作用
- .cpp.模板类继承不起作用
- 似乎头文件被忽略了/继承平原不起作用
- C++继承在堆栈上不起作用
- 使用继承时,带有 CRTP 的类型定义不起作用
- 类继承代码不起作用
- C++11构造函数继承不起作用
- c++中的继承不起作用.编译以下c++代码时发生链接器错误
- 使用模板时,继承不起作用
- 派生类的继承方法不起作用
- 具有继承的重载方法/运算符不起作用