Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么我不能在C++类中声明一个空构造函数,它从一个私有构造函数扩展到一个 我试图理解继承的私有构造函数的用法,我对C++是相当新的,并且在测试中,事情已经进入以下: vestigial.cc: In constructor ‘ExtraSample::ExtraSample()’: vestigial.cc:34:16: error: no matching function for call to ‘Sample::Sample()’ ExtraSample() {};_C++_Inheritance_C++11 - Fatal编程技术网

为什么我不能在C++类中声明一个空构造函数,它从一个私有构造函数扩展到一个 我试图理解继承的私有构造函数的用法,我对C++是相当新的,并且在测试中,事情已经进入以下: vestigial.cc: In constructor ‘ExtraSample::ExtraSample()’: vestigial.cc:34:16: error: no matching function for call to ‘Sample::Sample()’ ExtraSample() {};

为什么我不能在C++类中声明一个空构造函数,它从一个私有构造函数扩展到一个 我试图理解继承的私有构造函数的用法,我对C++是相当新的,并且在测试中,事情已经进入以下: vestigial.cc: In constructor ‘ExtraSample::ExtraSample()’: vestigial.cc:34:16: error: no matching function for call to ‘Sample::Sample()’ ExtraSample() {};,c++,inheritance,c++11,C++,Inheritance,C++11,使用它编译:g++-std=c++11 vestigial.cc 代码如下: #include <iostream> #include <memory> #include <string> #include <vector> using namespace std; class Sample { public: ~Sample(){ cout << name << " died " <<

使用它编译:g++-std=c++11 vestigial.cc

代码如下:

#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;

class Sample {
public:
    ~Sample(){
        cout << name << " died " << endl;
    };
    void what() {
        cout << name << " hat" << endl;
    }
private:
    Sample(const string n) {
        name = n;
    };
    friend class SampleOwner;
    string name;
};


class SampleOwner {
public:
    static Sample* createSample(const string n) {
        return new Sample(n);
    }
};

class ExtraSample : Sample {
public:
private:
    ExtraSample() {};
};
总之-为什么此代码无效


谢谢大家!

初始化派生类时,必须首先初始化基类。通过在派生类构造函数的ctor初始值设定项中提及基类的名称,可以指定要调用的基类构造函数。如果没有显式指定,编译器将尝试调用基类的默认构造函数

但是,该基类没有默认构造函数,因此会显示错误消息。请注意,无论如何您都不能调用Sample::Samplestring,因为它是私有的,所以实际上根本不可能从Sample派生

如果希望基类的构造函数只能由派生类调用,请改为使其受保护

为什么代码无效

调用方无法访问专用构造函数

有几种方法可以使调用私有基类构造函数成为可能

修改基类以将派生类命名为友元

将命名构造函数添加到基类中作为受保护的或公共的,它可以调用派生构造函数。命名构造函数惯用方法是静态的

修改基类以将函数命名为友元

修改要保护的私有构造函数


防止继承的唯一方法之一是使构造函数私有化基类中没有默认的构造函数,因此编译器不知道调用哪个构造函数。在这种情况下,您需要隐式调用基类的构造函数,但因为它是私有的,所以您不能。添加公共构造函数确实允许我进行编译,但这似乎违背了拥有私有构造函数的目的,从第一条注释可以看出这一点。