c++ c++-faq copy-constructor assignment-operator rule-of-three
在使用模板时,我遇到了一个需要,可以从继承的类访问基类构造函数来创建对象,以减少复制/粘贴操作.我想通过using关键字以与功能案例相同的方式做到这一点,但这不起作用.
class A
{
public:
A(int val) {}
};
class B : public A
{
};
class C : public A
{
public:
C(const string &val) {}
};
class D : public A
{
public:
D(const string &val) {}
using A::A; // g++ error: A::A names constructor
};
void main()
{
B b(10); // Ok. (A::A constructor is not overlapped)
C c(10); // error: no matching function to call to 'C::C(int)'
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:在声明了继承类中的新构造函数后,有没有办法导入基类构造函数?
或者只有一个替代方法来声明新构造函数并从初始化列表中调用基础构造函数?
可能重复:
如何在C++中使用基类的构造函数和赋值运算符?
class A
{
protected:
void f();
}
class B : public A
{
protected:
void f()
{
A::f();
}
}
Run Code Online (Sandbox Code Playgroud)
我们可以用这种方式使用父类的功能,但我不知道如何使用父类的运算符.
class A {
private:
A& operator=(const A&);
};
class B : public A {
public:
B& operator=(const A&) {
return *this;
}
};
int main() {
B b1;
B b2;
b1 = b2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给compilaton带来错误:
test.cpp: In member function 'B& B::operator=(const B&)':
test.cpp:16:5: error: 'A& A::operator=(const A&)' is private
test.cpp:19:20: error: within this context
test.cpp: In function 'int main()':
test.cpp:31:7: note: synthesized method 'B& B::operator=(const B&)'
first required here
Build error occurred, build is stopped
Run Code Online (Sandbox Code Playgroud)
由于B :: operator …
我有一个继承自另一个类的类,我希望调用[index]访问某些已分配存储的索引元素.
这是一个最小的例子:
class A
{
protected:
double *mem;
double operator[](const size_t index)
{
return mem[index];
}
}
class B : public A
{
void function()
{
double var = this->operator[](0);
}
}
Run Code Online (Sandbox Code Playgroud)
所以我在这里通过调用this->operator[](0)哪个方法来解决这个问题.
这是访问元素的正确方法,mem考虑到我无法从派生类访问该变量,还是有其他方法?
编辑:我认为我符合C++ 11可能很重要,所以不能打电话mem[0]?
编辑,模板类
如下所述,我看到的编译器错误没有出现在这个例子中,因为这里没有模板.
要重现编译器错误:
template <typename T>
class A
{
protected:
double *mem;
double operator[](const size_t index)
{
return mem[index];
}
}
template <typename T>
class B : public A<T>
{
void function()
{
double var = …Run Code Online (Sandbox Code Playgroud) 假设我有两个班级
Base 管理一些内存。它具有工作移动、交换、赋值和析构函数。Derived 不会添加任何需要管理的新内容(没有新的内存分配)。
class Base
{
public:
Base();
Base(const Base& other);
friend void swap(Base& a, Base& b);
Base(Base&& other);
protected:
int** some2Darray;
int w, h;
};
class Derived : public Base
{
public:
Derived();
//...?
};
Run Code Online (Sandbox Code Playgroud)
我是否需要在派生类中实现所有这些函数才能使它更好?如何重用基类中的这些函数?我不需要在这个类中管理更多的内存。
如果我将成员添加到派生类,这些函数会是什么样子?我应该完全重写所有这些函数,还是有某种方法可以使用例如“复制”基类,然后在复制构造函数中另外复制一个添加的成员?