是否可以为所有派生对象初始化抽象基类'protected成员而无需在所有派生类构造函数中编写相同的初始化列表?这样它就像所有派生对象的静态成员一样。我想要的是这样的东西(除了它不起作用)读取它像伪代码:
A.H
class A {
public:
A(string fn);
virtual ~A();
virtual void open_file() = 0;
protected:
string fileName;
};
A.cpp
A::A(string fn) : fileName {fn} {} //Initializer list is written only once here
A::~A() {}
B.h
class B : public A {
public:
B();
~B();
void open_file() const override;
};
B.cpp
B::B() {} //No initializer list for A::fileName here
void B::open_file() const {
ifstream SomeFile(fileName); //Use base class' protected member
..... //Do some stuff with open file
}
想象一下,C
派生的类没有A
的初始化列表,这里有一个不同的覆盖open_file
函数。
的main.cpp
string fname = {"foo.txt"};
A* APtr = new B(fname); //This initializes A's fileName for all derived objects as "foo.txt"
Aptr->open_file(); //B opens foo.txt
fname = "bar.txt";
A* A2Ptr = new C(fname); //Now fileName that both B and C consume is changed to "bar.txt"
A2Ptr->open_file(); //C opens bar.txt
APtr->open_file(); //B now opens bar.txt
答案 0 :(得分:1)
你从B:B();
中释放了构造函数,但是你试图使用它A* APtr = new B(fname);
所以编译器找不到任何匹配的构造函数。
为所有派生对象初始化抽象基类'protected成员,而不在所有派生类中编写相同的初始化列表
为什么不呢?
A.hpp
class A
{
public:
A( string fn = "") : fileName(fn){} // you can give an default path if prefered.
};
B.hpp
class B : public A
{
public:
B( string fn = "") : A( fn ) {} //c++11 feature: call base constructor.
}
的main.cpp
B* b = new B();
b->setFileName("foo.txt");
b->openFile();